Home > Software engineering >  Command to list reordered ls columns works in terminal but not through running a script?
Command to list reordered ls columns works in terminal but not through running a script?

Time:06-13

I'm trying to make a script that will print information of all files in a given directory in order of owner, group, filename, then permissions separated by commas. The code I wrote works fine when ran in terminal, but when I try to run it through a script with a directory given as $1, it only prints the owner name once and nothing else. What am I overlooking?

here's the code:

 ls -l | awk '{print $3, ",", $4, ",", $9, ", " $1}'

works fine in terminal, but

 ls -l "$1" | awk '{print $3, ",", $4, ",", $9, ", " $1}'

ran from $script.sh directoryname outputs only the user name once and that's it.

CodePudding user response:

Don't parse ls. Use stat instead

stat -c '%U,%G,%n,%A' "$1"/*

That puts the directory name in the output, so you might want to cd "$1" then use stat ... *


Another option: find

find "$1" -maxdepth 1 -type f -printf '%u,%g,%P,%M\n'
  • Related