Search code examples
linuxbashcommand-linesudo

How do I run a for loop on the command line as root in bash


I'm trying to run a simple for loop to check and display the temperature of several hard drives like so:

for drive in a b c d e f g; do hddtemp "/dev/sd$drive"; done

This works great if I su to root, but I'd like to just be able to run it or other loop type one-line commands on the command line if possible where sudo might be required.
If I try

sudo for drive in a b c d e f g; do hddtemp "/dev/sd$drive"; done;

I get this error:

bash: syntax error near unexpected token `do'

Same error as above if I omit the final ; (semicolon)

Enclosing the command in " (double quotes) gives this result:

sudo: for drive in a b c d e f g; do hddtemp /dev/sdg; done: command not found

Enclosing the command in back-ticks (`)

sudo "`for drive in a b c d e f g; do hddtemp "/dev/sd$drive"; done`" 

gives an error for each instance of drive letter/spec specified:

/dev/sda: open: Permission denied followed by sudo: : command not found

Is it possible to run a for (or other loop) command as a command line one-liner sudo'ing or otherwise using my root credentials in bash?

Ubuntu linux 16.04LTS / GNU bash 4.3.46(1)


Solution

  • Don't put sudo before the for loop. The following works fine.

    for drive in {a..g}; do sudo hddtemp "/dev/sd$drive"; done