奇怪的错误
在linux下的shell脚本中,第一行一般会指明该脚本的执行程序名,以便为该脚本拥有执行权限时可以通过脚本名直接运行。
我在控制台上一般通过 sh 命令执行shell脚本,如sh xxx.sh;所以有次我新建一个shell脚本时,脚本第一行写的是#!/bin/sh,如下所示:
#!/bin/sh
####################################################################################
#File Name : xchmod.sh
#Author : Li Jinmiao
#Mail : beikejinmiao@gmail.com
#Created Time : 2015-08-31 09:40:32
#Description : 'chmod +x' for python's file and shell script for given path
####################################################################################
path=$1
if [ -z "${path}" ]; then
path=`pwd` ##若没指定目录,则默认为当前工作目录
fi
##判断目录存在性
if [ ! -d ${path} ]; then
echo "'${path}' is not exist Or '${path}' is not a directory!"
exit 1
fi
##判断目录操作权限
if [ ! -x ${path} -o ! -w ${path} ]; then
echo "You have no right to operate the directory of '$path'!"
exit 1
fi
reg=".(py|sh)$"
rlt=1
for file in ${path}/*
do
if [ ! -x ${file} ]; then
if [[ ${file} =~ $reg ]]; then
`chmod +x ${file}` && echo "chmod +x" \"${file}\"
rlt=$?
fi
fi
done
[ $rlt -eq 1 ] && echo "Nothing to do."
echo "Done."
执行结果如下:
瞬间懵逼了。
看错误提示应该是32行的问题。
问题所在
原来是因为ubuntu默认的shell是dash,我也只是听说过一点点而已,因为大家都用bash,我就一直用了bash。
没想到dash和bash下shell脚本的语法有些差距,我正好给撞上了。dash和bash还有很多不同,有些命令使用也不太相同。这有篇文章介绍的不错:[转]Dash与Bash的语法区别。
把脚本第一行换成 #!/bin/bash 就没事了。或者修改系统的默认shell。
修改Ubuntu默认shell
有两种方式
1)ln -s
强制把/bin/sh的软链接改到bash中: sudo ln -s /bin/bash /bin/sh
2)dpkg-reconfigure dash
在Ubuntu中建议使用这个方法:sudo dpkg-reconfigure dash,弹出来个选择项,把“dash设为默认shell”选择no。
下面是效果图
————————————————
版权声明:本文为CSDN博主「beikejinmiao」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/beikejinmiao/article/details/48711049