在Linux中没有命令行参数的情况下运行Shell脚本
问题描述:
我想运行一个Shell脚本,但遇到了问题。我想运行某些代码集,当我提供参数和剩余应该运行,如果我不通过任何参数。 我想与ARGS运行部分:在Linux中没有命令行参数的情况下运行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
,这部分没有任何ARGS
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
...
感谢您的回复......您能解释为什么我的逻辑失败了吗? – Ismail
假设发布的代码是完整的脚本,那么明显在第一部分'##'后总是为零,或者是因为它从一开始就是零,或者因为你有'shift'所有参数,所以第二部分无条件运行。 – AlexP
感谢您的解释。 – Ismail