Note that there are some explanatory texts on larger screens.

plurals
  1. POError handling in bash/expect script
    primarykey
    data
    text
    <p>Pasted below is a bash script, combined with expect code, which:</p> <ul> <li>connects to remote host via ssh, collects files and prepare tgz file;</li> <li>copy tgz file from remote host to local machine;</li> <li>connects to remote host via ssh again and remove previously created tgz file;</li> <li>finally, extract tgz file on local machine.</li> </ul> <p>Everything works, if passed arguments are valid (i.e., <code>$host</code>, <code>$user</code>, and <code>$pass</code>). If one of them is incorrect, script hangs. I wonder how to include some error handling (e.g., in $cmd1) to terminate script with message if username (or password) is incorrect?</p> <p>Thanks in advance for any pointers.</p> <pre><code>#!/bin/bash prog=$(basename $0) NO_ARGS=0 E_OPTERROR=85 # Script invoked with no command-line args? if [ $# -eq "$NO_ARGS" ]; then echo "Usage: $prog [-h host] [-u username] [-p password]" echo " $prog -help for help." exit $E_OPTERROR fi showhelp() { echo "Usage: $prog [-h host] [-u username] [-p password]" echo " -h: host" echo " -u: username" echo " -p: password" echo " -help: this help message" exit 2 } user="" host="" pass="" now=$(date +"%m-%d-%Y") dir="data_$now" file="data.tgz" while getopts "h:u:p:help" name; do case $name in h) host=$OPTARG ;; u) user=$OPTARG ;; p) pass=$OPTARG ;; help) showhelp $0 ;; esac done if [ -d "$dir" ]; then rm -R $dir mkdir $dir else mkdir $dir fi cmd1=$(expect &lt;&lt; EOF spawn ssh $user@$host expect "password: " send "$pass\n" expect "$ " send "cd /tmp\n" expect "$ " send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n" expect "$ " send "logout" EOF) cmd2=$(expect &lt;&lt; EOF spawn scp $user@$host:/tmp/$file $dir expect "password: " send "$pass\n" expect "$ " EOF) CMD3=$(expect &lt;&lt; EOF spawn ssh $user@$host expect "password: " send "$pass\n" expect "$ " send "cd /tmp\n" expect "$ " send "rm $file\n" expect "$ " send "logout" EOF) echo "$cmd1" echo "$cmd2" echo "$cmd3" cd $dir tar -xzf $file rm $file count=$(ls -1 | wc -l | awk '{gsub(/^ +| +$/, "")}1') cd .. #clear echo "All done. Extracted $count *.net files." </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload