0

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!

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
Mikael
  • 171
  • 2
  • 12

1 Answers1

1

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"}]
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Thanks @glenn!!!for the second solution (using: set dirs...), if I want to add another command which is not "du -ckhx" and which will run only for once, where should better I insert it? That is, if I want to add the "sudo yum clean all" at the beginning. Should it better be after "set cmds [" and befoe "lmap dir $dires"? as a new item in the list. – Mikael Feb 12 '21 at 15:17
  • is lmap a known command? as it's giving me an error that lmap is not a valid command! (it's just out of curiosity, as I'm already using the other method having the commands separated and it works :) ) – Mikael Feb 24 '21 at 14:13
  • lmap was released in Tcl 8.6, so your expect is probably very old. In an interactive expect session, what does `info patchlevel` return? – glenn jackman Feb 24 '21 at 14:31
  • `lmap` is basically this, except implemented in C: `proc lmap {varname list script} {upvar $varname var; set result {}; foreach var $list {lappend result [uplevel $script]}; return $result}` -- except that it can take a _varlist_ not just a varname, and multiple _varlist list_ pairs like foreach does. http://www.tcl-lang.org/man/tcl8.6/TclCmd/lmap.htm – glenn jackman Feb 24 '21 at 14:38