我正在尝试运行 Shell 脚本,但遇到了问题。我想在提供参数时运行某些代码集,如果我不传递任何参数,则剩余的代码应该运行。 我想用参数运行的部分:
#!/bin/bash
while [[ "$1" != "" ]]; do
case "$1" in
-c ) cat /proc/cpuinfo | grep cores
;;
-d ) fdisk -l | grep Disk | awk '{print $1,$2,$3,$4}' #fdisk -l 2> /dev/null | grep Disk | grep -v identifier
;;
esac
shift
done
这部分没有任何参数
while [[ $# -eq 0 ]]; do
echo PART 2 $#
cat /proc/cpuinfo | grep cores
fdisk -l | grep Disk | awk '{print $1,$2,$3,$4}' #fdisk -l 2> /dev/null | grep Disk | grep -v identifier
break
done
我相信问题出在循环条件上,但我不明白是什么?
最佳答案
if [[ -n "$1" ]]; then
#
# "$1" is not empty. This is the part which runs when one or more
# arguments are supplied.
#
while [[ -n "$1" ]]; do
case "$1" in
-c) cat /proc/cpuinfo | grep cores
;;
-d) LC_ALL=C fdisk -l | grep Disk | awk '{print $1,$2,$3,$4}'
#LC_ALL=C fdisk -l 2> /dev/null | grep Disk | grep -v identifier
;;
esac
shift
done
exit
fi
#
# "$1" is empty. The following code runs when no arguments are supplied.
#
echo PART 2 $#
cat /proc/cpuinfo | grep cores
LC_ALL=C fdisk -l | grep Disk | awk '{print $1,$2,$3,$4}'
#LC_ALL=C fdisk -l 2> /dev/null | grep Disk | grep -v identifier
注1:未经测试。
注释 2:每当您觉得需要解析命令的输出以查找某些单词或短语时,最好在默认语言环境中运行该命令,并在命令前面加上 LC_ALL=C 前缀。这样,您在法语语言环境中就不会感到惊讶,例如,fdisk
说 Disque
...
关于linux - 在 Linux 中运行不带命令行参数的 Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43171405/