Mikael
Mikael

Reputation: 191

How to assign multi commands to a spawn in UNIX?

How can I execute all these commands in 1 spawn?

These are the commands:

sudo du -ckhx /opt/ | sort -rh | head -10
sudo du -ckhx /usr/ | sort -rh | head -10
sudo du -ckhx /var/ | sort -rh | head -10

This is the spawn command:

 spawn ssh -o StrictHostKeyChecking=no $username@$ip $commands

After the spawn, I'm using expect for the password...

I know I can assign them to 1 variable, such as:

set commands "sudo du -ckhx /opt/ | sort -rh | head -10 && sudo du -ckhx /usr/ | sort -rh | head -10 &&..."

but it will be so long if I have many of those commands (for some other directories I want).

Thanks!

Upvotes: 0

Views: 94

Answers (1)

glenn jackman
glenn jackman

Reputation: 246774

Perhaps:

set commands {
    sudo du -ckhx /opt/ | sort -rh | head -10
    sudo du -ckhx /usr/ | sort -rh | head -10
    sudo du -ckhx /var/ | sort -rh | head -10
}
spawn ssh -o StrictHostKeyChecking=no $username@$ip sh -c $commands

Building on Nate's comment:

set dirs { /opt  /usr  /var }
set cmds [lmap dir $dirs {
    format {sudo du -ckhx %s | sort -rh | head -10} $dir
}]

spawn ssh ... sh -c [join $cmds \n]

I'd recommend you get a bit familiar with syntax if you're going to be developing expect code.

To add commands, you use Tcl list commands.

  • append: lappend cmds {echo "this is the last command"}
  • prepend: set cmds [linsert $cmds 0 {echo "first command"}]

Upvotes: 1

Related Questions