![如何创建 shell 脚本来处理 ls -l /somedir 等命令](https://linux22.com/image/77252/%E5%A6%82%E4%BD%95%E5%88%9B%E5%BB%BA%20shell%20%E8%84%9A%E6%9C%AC%E6%9D%A5%E5%A4%84%E7%90%86%20ls%20-l%20%2Fsomedir%20%E7%AD%89%E5%91%BD%E4%BB%A4.png)
到目前为止,我的脚本可以处理该ls
命令并返回目录中的文件。现在我试图让它处理像ls -l /tmp
.有什么帮助吗?
到目前为止我的脚本:
#!/bin/bash
#set -x
clear
read -p "type a command: " file
read -r -a prog <<<"$file"
IFS=: read -r -a paths <<<"$PATH"
for val in "${prog[@]}" ; do
for path in "${paths[@]}"; do
[[ -x $path/$val ]] && "$path/$val" "$@"
done
done
答案1
也许是这样的:
#!/usr/bin/env bash
clear
IFS=: read -r -a paths <<<"$PATH"
read -p "type a command: " cmd
read -d ' ' file <<<"$cmd" #the first component of command
for path in "${paths[@]}"; do
[ -x "$path/$file" ] && eval "$path/$cmd"
done
这基本上为每个可能的路径解析运行输入的命令。