我正在尝试在Ubuntu中编写一个极其简单的脚本,它将允许我传递它一个文件名或目录,并且能够在它是一个文件时做一些特定的事情,当它是一个目录时做一些其他的事情。我遇到的问题是,当目录名,或可能文件,有空格或其他可转义字符在名称中。
下面是我的基本代码,还有几个测试。
#!/bin/bash
PASSED=$1
if [ -d "${PASSED}" ] ; then
echo "$PASSED is a directory";
else
if [ -f "${PASSED}" ]; then
echo "${PASSED} is a file";
else
echo "${PASSED} is not valid";
exit 1
fi
fi
这是输出:
andy@server~ $ ./scripts/testmove.sh /home/andy/
/home/andy/ is a directory
andy@server~ $ ./scripts/testmove.sh /home/andy/blah.txt
/home/andy/blah.txt is a file
andy@server~ $ ./scripts/testmove.sh /home/andy/blah\ with\ a\ space.txt
/home/andy/blah with a space.txt is not valid
andy@server~ $ ./scripts/testmove.sh /home/andy\ with\ a\ space/
/home/andy with a space/ is not valid
所有这些路径都是有效的,并且存在。
至少在编写代码时不要使用这棵浓密的树:
#!/bin/bash
PASSED=$1
if [ -d "${PASSED}" ]
then echo "${PASSED} is a directory";
elif [ -f "${PASSED}" ]
then echo "${PASSED} is a file";
else echo "${PASSED} is not valid";
exit 1
fi
当我把它放入一个文件“xx.sh”,并创建一个文件“xx sh”,并运行它,我得到:
$ cp /dev/null "xx sh"
$ for file in . xx*; do sh "$file"; done
. is a directory
xx sh is a file
xx.sh is a file
$
如果您遇到了问题,您应该通过添加以下内容来调试脚本:
ls -ld "${PASSED}"
这将显示ls对传递脚本的名称的想法。
至少在编写代码时不要使用这棵浓密的树:
#!/bin/bash
PASSED=$1
if [ -d "${PASSED}" ]
then echo "${PASSED} is a directory";
elif [ -f "${PASSED}" ]
then echo "${PASSED} is a file";
else echo "${PASSED} is not valid";
exit 1
fi
当我把它放入一个文件“xx.sh”,并创建一个文件“xx sh”,并运行它,我得到:
$ cp /dev/null "xx sh"
$ for file in . xx*; do sh "$file"; done
. is a directory
xx sh is a file
xx.sh is a file
$
如果您遇到了问题,您应该通过添加以下内容来调试脚本:
ls -ld "${PASSED}"
这将显示ls对传递脚本的名称的想法。