Shell 脚本:如何将脚本的命令行参数传递给它调用的命令?

Shell Script :How to pass script's command-line arguments through to commands that it invokes?

到目前为止,“ls”工作正常,我获取了目录中的所有文件。但是现在我希望当我执行 ./myscript ls -l /somedir 时得到与我在终端输入 ls -l /somedir 时得到的结果相同的结果。

有什么办法可以做到吗? 到目前为止,这是我的代码..

#!/bin/sh
clear

echo ""
read  -p "type something :  " file
    echo""
    IFS=:
    for dir in $PATH ; do  

        if [ -x "$dir/$file" ]
        then

        echo ""
          exec "$dir/$file" 

        fi
        done

据我了解(这涉及大量猜测,因为问题没有明确提出),你的问题是命令行参数没有通过。

使用"$@"访问它们:

#!/bin/bash
prog=; shift
IFS=: read -r -a paths <<<"$PATH"
for path in "${paths[@]}"; do
  [[ -x $path/$prog ]] && "$path/$prog" "$@"
done

然后,运行 yourscript ls -l /foo 实际上会将 -l/foo 传递给它们创建的 ls 的任何实例。