linux - 在 Linux 中运行不带命令行参数的 Shell 脚本

标签 linux bash shell while-loop

我正在尝试运行 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 前缀。这样,您在法语语言环境中就不会感到惊讶,例如,fdiskDisque...

关于linux - 在 Linux 中运行不带命令行参数的 Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43171405/

相关文章:

linux - 保持 SSH 在 Windows 10 Bash 上运行

linux - Unix - 如何对一个词使用 cut -d

linux kallsyms R 符号不显示

linux - 如何读取包含字符串的文件并在目录中找到它

linux - prctl(pr_set_dumpable, 1) 有明显的副作用吗?

linux - 一次全部输出标准输出,而不是逐行输出

linux - 空间作为从 bash 编程的参数

linux - 如何在 shell 文件中使用 awk 的 $0 变量

linux - 尝试迭代存储在变量中的文件

python - 完全独立地从python脚本重启wifi接口(interface)