编辑:我想循环遍历名称中包含变量 c 的所有文件,但由于某种原因,此脚本循环遍历目录中的所有文件......不应该是“$c“仅匹配包含 c 的文件名?
我还想解析 $b 和 $e 破折号之间的数字
我认为这仍然是对三个变量访问不当的问题
while getopts ":a:b:c:" arg; do
case "${arg}" in
a) a="$OPTARG";;
b) b="$OPTARG";;
c) c="$OPTARG";;
esac
done
echo "Locally using begin: $a , end: $b, and customer: $c"
cd "/opt/data"
a="$(echo "$a" | sed -e 's/[-]/\\&/g')"
b="$(echo "$b" | sed -e 's/[-]/\\&/g')"
ssh -o ... -i $Host <<EOF
echo "Remotely using begin: $a , end: $b, and customer: $c"
find . -type f -name "*$c*" -print0 | while IFS= read -r -d $'\0' file;
do
echo $file
done
答案1
您的脚本存在几个问题。
首先是getopts 在遇到第一个非选项参数时停止处理。由于您尚未将其声明-e
为选项参数,因此它将未经处理,并且不会为 分配任何值c
。考虑:
$ cat myscript
#!/bin/bash
printf 'Processing option arguments:\n'
while getopts ":a:b:c:" arg; do
case "${arg}" in
a) a="$OPTARG"; echo "\$a is $a";;
b) b="$OPTARG"; echo "\$b is $b";;
c) c="$OPTARG"; echo "\$c is $c";;
esac
done
printf 'Done.\n\n'
shift $((OPTIND - 1))
printf 'Remaining (non-option) arguments:\n'
printf '%s\n' "$@"
按照建议运行你上面的评论:
$ ./myscript -b 06-30-20-18-10 -e 06-30-20-23-59 -c name otherarg whatever
Processing option arguments:
$b is 06-30-20-18-10
Done.
Remaining (non-option) arguments:
06-30-20-23-59
-c
name
otherarg
whatever
第二,即使在本地 shell 中为变量 c 赋值,引用 heredoc 的结束标记 'EOF'
阻止本地 shell 扩展它. 因此远程 shell 接收$c
,并将其扩展为其(几乎肯定是空的)值。
纠正两个问题:
$ cat myscript
#!/bin/bash
printf 'Processing option arguments:\n'
while getopts ":a:b:c:e:" arg; do
case "${arg}" in
a) a="$OPTARG"; echo "\$a is $a";;
b) b="$OPTARG"; echo "\$b is $b";;
c) c="$OPTARG"; echo "\$c is $c";;
e) e="$OPTARG"; echo "\$e is $e";;
esac
done
printf 'Done.\n\n'
shift $((OPTIND - 1))
printf 'Remaining (non-option) arguments:\n'
printf '%s\n' "$@"
ssh localhost << EOF
printf '%s\n' "$a" "$b" "$c" "$e"
EOF
然后
$ ./myscript -b 06-30-20-18-10 -e 06-30-20-23-59 -c name
Processing option arguments:
$b is 06-30-20-18-10
$e is 06-30-20-23-59
$c is name
Done.
Remaining (non-option) arguments:
Pseudo-terminal will not be allocated because stdin is not a terminal.
Enter passphrase for key '/home/steeldriver/.ssh/id_rsa':
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-143-generic x86_64)
You have mail.
06-30-20-18-10
name
06-30-20-23-59