Search code examples
bashawkls

awk in bash with ls and variable


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'

Solution

  • 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}'