1

I have a simple script to convert a text file with colour escape sequences to the actual characters. It works if I run it directly, but not with sudo.

To set up the scripts:

test.txt

\e[1;34mTEST\e[0m\n

test.sh (+x)

printf "`cat $1`" > test.bin
  • Running ./test.sh test.txt then cat test.bin gives TEST in blue.
  • Running sudo ./test.sh test.txt then cat test.bin gives \e[1;34mTEST\e[0m\n

What's going on here?

Notes:

  • Running sudo bash -c "./test.sh test.txt" gives the right output - why is that?
  • echo -e behaves the same as printf
2

Try sudo -i ./test.sh.

I don't know if there's there a specific need for having the colour coded string in a separate file then writing it out to another one, but the following works fine withou the -i flag:

#!/bin/bash
string="\e[1;34mTEST\e[0m\n"
printf "${string}"
  • Cool, that works - I'm interested in why it's happening as much as workaround though – Greg Oct 10 '14 at 8:21
  • BTW it's in a separate file because there are several different strings, each about 20 KB – Greg Oct 10 '14 at 8:22
  • I believe it has to do with TERM settings. Usually by default sudo has Defaults env_reset set in its configuration. When you're calling the script via sudo those settings are missing. By using sudo -i or sudo bash -c "..." they are being set. – Gene Oct 10 '14 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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