如何"如果"是假的

时间:2015-07-02 13:44:35

标签: bash

我学习BASH脚本,我遇到了问题。我写了一个生成器,检查是否有与给定名称相同的脚本,如果没有,它会生成一个,使其可执行并给它正确的shebang。但它不起作用。我希望它在已经有一个具有该名称的脚本时退出。你能告诉我我做错了吗?

#!/bin/bash

clear

echo "Name the script"
read name
echo "What shell? (bash/sh)"
read type
if [ -e ./$name ]

then
    echo "You already have that script"
    read    
    exit
else
    touch $name
    chmod 755 $name
fi

case $type in
"bash") echo '#!/bin/bash' > $name ;;
"sh") echo '#!/bin/bash' > $name ;;
*) echo "I don't know what do you want" ;;
esac
vim $name

1 个答案:

答案 0 :(得分:0)

还有一个额外的read阻碍了你:

if [[ -e ./$name ]]
then
    echo "'./$name' already exists"    # <<<< always report the name
    # read      <<<< This is the line which is causing problems
    exit 1   #  <<<< indicate there was an error
else
    touch "$name"
    chmod 755 "$name"
fi

引用文件名,因为它们包含嵌入的空格(如果您使用[[ ]],则不需要围绕变量。

另请注意,#!的{​​{1}}行有误(您正在使用sh

编辑: 如果您的系统上有bash,那么使用/etc/shells菜单是一个很好的练习。试试这个:

select

您也可以考虑使用#!/bin/bash read -p "Name the script: " name if [[ -e ./$name ]] then echo "'./$name' already exists" # <<<< always report the name # read <<<< This is the line which is causing problems exit 1 # <<<< indicate there was an error else touch "$name" chmod 755 "$name" fi declare -a shells i=0 while read shell do if [[ $shell != \#* && $shell != "" ]] then shells[i++]="$shell" fi done < /etc/shells PS3='Please select the shell: ' select type in "${shells[@]}" QUIT do echo "You selected $type" if [[ $type == QUIT ]] then exit 2 fi break done echo "#!$type" > "$name" vim $name 而不是硬编码$EDITOR

相关问题