为了得到一个认识:
- 你的脚本将一个参数(文件的名称)。
- 你问你是否想让该文件成为可执行文件。
- 如果答案是'是',则使文件可执行。
- 否则,你不。
你想验证文件是否也存在?
我想了解你的逻辑。这是什么:
if [ "$(ls -A /home/user/bin/)" ];
假设要做。 [ ... ]
语法是一个测试。而且,它必须是您看到的有效测试here之一。例如,有一个测试:
这意味着,我可以看到,如果你的文件是/home/user/bin
下:
target="/home/user/bin"
if [ -e "$target/$file" ] # The "-e" test for existence
then
echo "Hey! $file exists in the $target directory. I can make it executable."
else
echo "Sorry, $file is not in the $target directory. Can't touch it."
fi
你$(ls -A /home/user/bin/)
会产生一个文件列表。这不是一个像-e
这样的有效测试,除非它发生在您的列表中的第一个文件与-e
或-d
类似。
试着澄清你想要做什么。我认为这是沿着你想要的线条更多的东西:
#! /bin/bash
target="/home/user/bin"
if [ -z "$1" ] # Did the user give you a parameter
then
echo "No file name given"
exit 2
fi
# File given, see if it exists in $target directory
if [ ! -e "$target/$1" ]
then
echo "File '$target/$1' does not exist."
exit 2
fi
# File was given and exists in the $target directory
read -p"Do you want $target/$1 to be executable? (y/n)" continue
if [ "y" = "$continue" ]
then
chmod +x "$target/$1"
fi
注意我如何使用测试,如果测试失败,我只是退出程序。这样,我不必在if/then
语句中嵌入if/then
语句。
Downvoted。如果你使用“#!/ bin/bash”shebang,则使用''[]''而不是'[[]]''。否则,你必须引用参数,例如''if [[! -f $ target]];''或者''if [! -f“$ target”];''。 chmod行也是错误的,它必须是''chmod + x“$ target”''。不要忘记''if [[$ CONT ='y']];''。 –
哎呀,刚注意到一个错字。它应该是“使用''[[]]''而不是''[]''”。我现在正在投票,因为你已经修复了你的代码;)如果有人没有明白,请访问[此链接](http://mywiki.wooledge.org/BashPitfalls#A.5B_.24foo_.3D_。 22bar.22_.5D) –