2013-12-12 179 views
1

我想编译一个脚本,将读取用户输入,并检查后的y/n语句文件。然后它将使文件可执行。我想用我的剧本问题是有条件的排序,但看看自己:Bash脚本 - 嵌套如果声明如果文件不存在

target=/home/user/bin/ 

cd $target 
read -p "This will make the command executable. Are you sure? (y/n)" CONT 
if [ "$CONT" == "y" ]; 
then 
    chmod +x $1 
    echo "File $1 is now executable." 
else 
    if [ "$(ls -A /home/user/bin/)" ]; 
    then 
    echo "File not found." 
    else 
    echo "Terminating..." 
    fi 
fi 

正如我所说的,我需要的脚本打印Y/N语句之后扫描文件。该脚本工作得很好,但它仍然给出了“文件现在可执行”,即使参数文件不存在(但只是在echo'd文本后给标准系统“无法找到文件”消息)。

回答

4

你的脚本大部分是正确的,你只需要检查文件是否先存在。另外,在shell脚本中使用cd并不是最佳实践,这里不需要。

所以重新写它

#!/bin/bash 
target="/home/user/bin/$1" 

if [[ ! -f $target ]]; then 
    echo "File not found." 
else 
    read -p "This will make the command executable. Are you sure? (y/n) " CONT 
    if [[ $CONT == "y" ]]; then 
     chmod +x "$target" 
     echo "File $1 is now executable." 
    else 
     echo "Terminating..." 
    fi 
fi 
+0

Downvoted。如果你使用“#!/ bin/bash”shebang,则使用''[]''而不是'[[]]''。否则,你必须引用参数,例如''if [[! -f $ target]];''或者''if [! -f“$ target”];''。 chmod行也是错误的,它必须是''chmod + x“$ target”''。不要忘记''if [[$ CONT ='y']];''。 –

+0

哎呀,刚注意到一个错字。它应该是“使用''[[]]''而不是''[]''”。我现在正在投票,因为你已经修复了你的代码;)如果有人没有明白,请访问[此链接](http://mywiki.wooledge.org/BashPitfalls#A.5B_.24foo_.3D_。 22bar.22_.5D) –

1

为了得到一个认识:

  • 你的脚本将一个参数(文件的名称)。
  • 你问你是否想让该文件成为可执行文件。
  • 如果答案是'是',则使文件可执行。
  • 否则,你不。

你想验证文件是否也存在?

我想了解你的逻辑。这是什么:

if [ "$(ls -A /home/user/bin/)" ]; 

假设要做。 [ ... ]语法是一个测试。而且,它必须是您看到的有效测试here之一。例如,有一个测试:

  • -e file:如果文件存在,则为真。

这意味着,我可以看到,如果你的文件是/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语句。

+0

Downvoted为好。阅读我的[评论](http://stackoverflow.com/questions/20532980/bash-script-nested-if-statement-for-if-file-doesnt-exist#comment30704265_20533317),看看为什么你的报价是错误的。 –

+0

我通常使用'[[...]]',但是'[['不是在'['是'时'test'的别名。 (他们都是BASH内置的)。对于初学者来说,使用'test'手册是非常方便的。我会更新我的答案,以确保我所引用的所有内容。 –

+0

不,建议初学者使用''[[]]''。首先,如果他们忘记在''[[]]'中引用一个变量,那么没有错误会发生,事实上,这是正确的做法。另一个原因是人们通常会学习另一种编程语言,其中条件与“test”命令不同。所以他们会期望''[]''是一些特殊的语法,但事实并非如此。在寻求帮助时,你应该“帮助”[''。如果你想获得所有可能的标志列表,那么使用''man bash''并搜索''CONDITIONAL EXPRESSIONS''。 –