Search This Blog

Saturday, February 26, 2011

login into a directory after sshing into a machine

To login into a machine via ssh and cd into a particular directory immediately afterwards, use
ssh -t user@machine.name 'cd ~/destination/directory && exec /bin/bash --login -i'
The -t option forces the ssh to open a pseudo-terminal. Without the -t option, ssh does not open the pseudo-terminal when a command is specified.

Commands can also contain variable names. For example,
export DYNAMIC=${PWD#$HOME/}
ssh -t user@machine.name "cd ~/$DYNAMIC && exec bash --login -i"
Other possible uses of the -t option

To see the output of top of a remote machine, use
ssh -t user@remote.machine.name top

Wednesday, February 02, 2011

Add a number to a variable in shell script

Consider the following shell script
$cat add_variables_02.sh
#! /bin/sh
ov=10;
nv=$((ov+3)); echo $nv
((nv=ov+3)); echo $nv
nv=$ov+3; echo $nv
nv=`expr $ov+3`; echo $nv
nv=`expr $ov + 3`; echo $nv
Execute in a shell
$bash add_variables_02.sh 
13
13
10+3
10+3
13
The first two methods nv=$((ov+3)) or ((nv=ov+3)) are faster than the fifth method nv=`expr $ov + 3` as the former uses bash's own feature and the later runs an external command in a subprocess.

Also, note that spaces are needed before and after the '+' character when expr is used.

Tested in Debian Wheezy machine using bash 4.2-1

Further reading
  1. info coreutils 'expr invocation'
  2. man expr

Special thanks to the anon 2011-08-24 5:06 AM for providing the first two methods.

Followers