Bash脚本 - 嵌套如果If文件的语句不存在

时间:2013-12-12 00:51:00

标签: bash if-statement nested

我正在尝试编译一个读取用户输入的脚本,并检查y / n语句后面的文件。然后它将使文件可执行。我认为我的脚本问题是条件排序,但请自行查看:

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文本后给标准系统“找不到文件”消息)。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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语句。