linux 如何将bash命令存储为文件中键的值,然后读取文件并使用bash脚本执行命令?

ercv8c1e  于 2023-05-22  发布在  Linux
关注(0)|答案(1)|浏览(140)

我创建了一个bash脚本test.sh来检查一些端口是否正在侦听。因为我不想在shell脚本中硬编码端口或命令,所以我把它们都放在一个文件config_file中,就像键值对一样。让我在下面展示文件和schell脚本;

test.sh

#!/bin/bash
cat config_file| while read port command; do
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null ; then
        echo "" > /dev/null
    else
        eval "$command"
    fi
done

配置文件

80 /bin/bash /home/user/sample_script1.sh
22 /bin/bash /home/user/sample_script2.sh

这两个文件sample_script1.shsample_script2.sh都意味着touch一些示例文件。当我运行./test.sh时,示例文件被正确创建(意味着调用了sample_script1.shsample_script2.sh)。但我明白

./test.sh: line 8: This: command not found

在终端。原因是什么以及如何解决这个问题?

nlejzf6q

nlejzf6q1#

您可以将配置文件拆分到另一个字段,类似于:

#!/usr/bin/env bash

cat config.txt | {
  while read -r port shell command; do
    echo "$port"
    [[ -e "$shell" && -e "$command" ]] &&
    "$shell" "$command"
  done
}

如果它是一个文件,那么你可以不使用UUOC,只使用shell重定向,类似于:

#!/usr/bin/env bash

while read -r port shell command; do
  echo "$port"
  [[ -e "$shell" && -e "$command" ]] &&
  "$shell" "$command"
done < config.txt

或者,如果输入来自流/命令,则类似于:

#!/usr/bin/env bash

while read -r port shell command; do
  echo "$port"
  [[ -e "$shell" && -e "$command" ]] &&
  "$shell" "$command"
done < <(my_command_with_output)
  • 请确保没有windows文件结束又名回车或一些无形的字符从这两个文件的问题。

相关问题