Correct way to use Linux commands in bash script

半腔热情 提交于 2019-12-24 02:04:15

问题


What is the best and most correct way to use Linux commands in bash scripts in terms of path to it? Is that correct to use only ip addr show, relying on shell path, or should I find a path to the command first (like with whereis ip or command -v ip), assign the output to some variable and then use that?


回答1:


Personally, I just rely on the PATH and invoke "bare" commands.

If you don't trust the user's PATH, you can reset it to a minimal default:

PATH=$(/usr/bin/getconf PATH)

grep "$pattern" "$file"



回答2:


I tend to set the path to utilities at the top of my path, avoiding any dependency on PATH. One potential attack is to set the PATH before running a bash script. Setting the path for each utility is painful, but it can protect against that sort of attack.

In cases where you are authoring for multiple environments in which the utilities are found in different places, e.g. Debian and MacOS, I check for the path, e.g.

[ -f /usr/bin/grep ] && GREP=/usr/bin/grep || GREP=/bin/grep


来源:https://stackoverflow.com/questions/53196702/correct-way-to-use-linux-commands-in-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!