No colors are displayed when running bash -c "ls -l" (CentOS 7.2). I have an obscure reason to want to show the colors after all. Can I disable this... color suppression?


For anyone wondering about my obscure use case: I'm running the Parcellite clipboard manager, which supports "actions" in a context menu, and one of the actions I've defined is "Run terminal command" which opens a new terminal and runs a command stored on the clipboard. It is implemented in the following way (so that the command is allowed to contain all special characters except apostrophe):

# Parcellite recognizes %s only once; store in a variable to use twice
CMD='%s' gnome-terminal -e "$SHELL -c 'echo \\\$ \"\$CMD\"; eval \$CMD; exec $SHELL'"
# Or equivalently....
CMD='%s' gnome-terminal -e $SHELL' -c "echo \$ "$CMD"; eval $CMD; exec $SHELL"'

Because gnome-terminal can only run a single command and doesn't understand things like &&, I need to call bash -c ($SHELL -c) in order to interpret the command correctly and keep the shell running afterward (and since bash doesn't directly support that I have to also sneak in exec $SHELL at the end.)

up vote 3 down vote accepted

A somewhat more general-purpose answer is to change bash -c to bash -ci.  The -i option puts the shell into “interactive” mode, which causes it to read the user’s .bashrc file and process aliases.

It's not that colors are suppressed when you call ls that way, it's that colors are not enabled.

Your normal shell likely defines an alias for ls that includes --color=tty to enable colors, so just use that option when you call ls.

  • I see, bash aliases are disabled in bash -c. bash -c "ls -l --color=tty" works as expected. It's easy to forget that ls doesn't really mean ls! – Qwertie Nov 9 at 1:01

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.