我正在努力处理位置参数。似乎没有任何工作,然后我决定用 echo 做一些小事情,看看它是否真的有效,但事实并非如此。有人能解释一下为什么吗?(我将在这里省略shebang行和评论,以切入正题)
if [[ -e $1 ]]; then
echo $#
echo $1
fi
Run Code Online (Sandbox Code Playgroud)
当我输入脚本名称后跟一个或多个参数时,它不会返回任何内容。但是,下面的内容按预期返回了所有内容。我真的很茫然。
if [[ -e $0 ]]; then
echo $#
echo $1
fi
Run Code Online (Sandbox Code Playgroud)
为什么不识别 $0 以外的参数?
Bash 的手册页:
CONDITIONAL EXPRESSIONS
Conditional expressions are used by the [[ compound command
and the test and [ builtin commands to test file attributes
and perform string and arithmetic comparisons.
-e file
True if file exists.
Run Code Online (Sandbox Code Playgroud)
因此,如果您传递一个与现有文件不匹配的字符串作为第一个参数,则为[[ -e $1 ]]
false。
但是,由于$0
通常包含外壳程序或脚本的名称,[[ -e $0 ]]
因此更有可能为真。
(但并非在所有情况下。交互式 shell 可以作为登录 shell 启动,其中前导破折号$0
(例如-/bin/bash
),并且类似的东西/bin/sh -c '...' foo bar
也设置$0
为foo
,并且您可以在其中放置任何您想要的东西。)
您可能想要的测试是-n
:
string
-n string
True if the length of string is non-zero.
Run Code Online (Sandbox Code Playgroud)
所以,[[ -n $1 ]]
或者只是[[ $1 ]]
。
归档时间: |
|
查看次数: |
186 次 |
最近记录: |