这是一个非常简单的脚本
#!/usr/local/bin/bash
set -e
if [ "$#" -lt 1 ]
then
echo "Please insert at least one argument"
exit
else
echo -e "\c"
fi
if [ -h "$1" ]
then
echo "$1 is a symbolic link"
else
echo "$1 in not a symbolic link"
fi
~
我的问题是:如何更改脚本以识别多个参数?我有 4 个文件,我希望脚本返回
$1 is a symbolic link
$2 is not a symbolic link
$3 is not a symbolic link
ETC
我怎么能这样做呢?
答案1
使用与原始脚本相同的结构,您只需要迭代数组$@
(即命令行中给出的参数列表):
#!/usr/local/bin/bash
set -e
if [ "$#" -lt 1 ]
then
echo "Please insert at least one argument"
exit
else
echo -e "\c"
fi
for file in "$@"
do
if [ -h "$file" ]
then
echo "$file is a symbolic link"
else
echo "$file is not a symbolic link"
fi
done
同一件事的简化版本是:
#!/usr/bin/env bash
[ "$#" -lt 1 ] && printf "Please give at least one argument\n" && exit
for file
do
[ -h "$file" ] && printf "%s is a symbolic link\n" "$file" ||
printf "%s is not a symbolic link\n" "$file"
done
答案2
没人提到换班吗?
if [ x = "x$1" ] ; then
echo need at least one file
exit 1
fi
while [ x != "x$1" ] ; do
if [ -h "$1" ]; then
echo "$1 is a symbolic link"
else
echo "$1 is not a symbolic link"
fi
shift
done
答案3
您可以使用for循环处理传递给脚本的所有文件:
for f do
if [ -h "$f" ]; then
printf "%s is a symbolic link\n" "$f"
else
printf "%s is not a symbolic link\n" "$f"
fi
done
答案4
我阅读它的方式是如何让我的个人脚本采用多个参数,例如 wget 可以执行“wget url1 url2 url3”
将整个脚本粘贴到以下内容中,其中显示“来自我的脚本的行”,并将此文件保存为新脚本:
ARGUMENTS=$(echo "$@"| tr " " "\n") ; while read A; do "lines from my script";done < "$ARGUMENTS"
脚本的参数存储在变量 $@ 中。这个小脚本环绕您的脚本并多次运行它,每次将下一个参数传递给它。如果您当前的脚本引用 $1,您必须将其更改为 $A。