awk in bash with ls and variable

点点圈 提交于 2019-12-18 09:49:27

问题


I wanted to print only the name of files of a specific directory: In this way it works:

ls -g  --sort=size -r /bin | awk '{print $8,$9,$10,$11,$12,$13}'

but if I read the path variable it doesn't work:

read PATH
ls -g  --sort=size -r $(PATH) | awk '{print $8,$9,$10,$11,$12,$13}'
Command 'awk' is available in '/usr/bin/awk'

回答1:


It should be:

ls -g  --sort=size -r ${PATH} | awk '{print $8,$9,$10,$11,$12,$13}'

Notice the curly braces.

With $(..), it'll execute the command/function named PATH and substitute the result, which is not what you want.

Note that PATH is the poor choice for a variable name as it will overwrite the system variable with the same name and make the system commands unavailable (since the original PATH has gone now). I suggest you use some other name such as my_path:

read my_path
ls -g  --sort=size -r ${my_path} | awk '{print $8,$9,$10,$11,$12,$13}'



回答2:


This is exactly why you should not use UPPER_CASE_VARS. $PATH is a variable used by the shell to find executables on your system. As soon as you over-write it with user input, your script can no longer find anything that does not reside in whatever the input was. In this case, you entered /bin, so your script can find /bin/ls but awk is not there.

The command_not_found_handle (see /etc/bash.bashrc) stepped in to give you a suggestion.



来源:https://stackoverflow.com/questions/27555060/awk-in-bash-with-ls-and-variable

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