Bash – calling a command from script and maintain styling

bashls

I am calling a command from a script running on Linux. In this case, ls to list directory contents.

When I call ls from the script, I do a simple while loop to read the output line by line.

I then print the line using echo and double quotes e.g. echo "$line".
It does echo out each line but it loses all styling (colours).

How would I maintain the styling while still being able to process the lines my self?

Best Answer

There are two problems here. First of all, what you are doing is absolutely the wrong way to process the files in a directory and will break if your file names contain newlines or other strangeness. See http://mywiki.wooledge.org/ParsingLs for more.

That said, the colors of ls are optional. In many Linux distributions, the command ls is actually aliased to ls --color=tty which enables colors when ls is printing to a tty (as opposed to a while loop, for example). However, aliases are not enabled in scripts usually so when you run ls from your script, you're just running normal ls with no colors.

So, the first ugly workaround would be to call ls --color=always. That will let you echo with colors. However, this is almost certainly a bad idea as I mentioned in the first paragraph. For one thing, if you just want to print each line out, why don't you just run ls and forget the while loop?

If you do need to process the files for some other reason and still need to use ls as well, use globbing to get the list of files and then run ls on each of them manually:

for file in *; do
    ls -d --color=always -- "$file"
done

That will not break on weird file names and will still show you the colors as you requested.

Related Question