bprasanna
bprasanna

Reputation: 2453

Shell scripting shell inside shell

I would like to connect to different shells (csh, ksh etc.,) and execute command inside each switched shell.

Following is the sample program which reflects my intention:

#!/bin/bash
echo $SHELL
csh
echo $SHELL
exit
ksh
echo $SHELL
exit

Since, i am not well versed with Shell scripting need a pointer on how to achieve this. Any help would be much appreciated.

Upvotes: 4

Views: 2440

Answers (4)

Michaël Le Barbier
Michaël Le Barbier

Reputation: 6478

You can pass arbitrary complex scripts to a shell, using the -c option, as in

sh -c 'echo This is the Bourne shell.'

You will save you a lot of headaches related to quotes and variable expansion if you wrap the call in a function reading the script on stdin as:

execute_with_ksh()
{
  local script
  script=$(cat)
  ksh -c "${script}"
}

prepare_complicated_script()
{
   # Write shell script on stdout,
   #  for instance by cat-ting a here-document.
   cat <<'EOF'
echo ${SHELL}
EOF 
}

prepare_complicated_script | execute_with_ksh

The advantage of this method is that it easy to insert a tee in the pipe or to break the pipe to control the script being passed to the shell.

If you want to execute the script on a remote host through ssh you should consider encode your script in base 64 to transmit it safely to the remote shell.

Upvotes: 1

user1978011
user1978011

Reputation: 3589

If you want to execute only one single command, you can use the -c option

csh -c 'echo $SHELL'
ksh -c 'echo $SHELL'

If you want to execute several commands, or even a whole script in a child-shell, you can use the here-document feature of bash and use the -s (read commands from stdin) on the child shells:

#!/bin/bash
echo "this is bash"

csh -s <<- EOF
    echo "here go the commands for csh"
    echo "and another one..."
EOF
echo "this is bash again"
ksh -s <<- EOF
    echo "and now, we're in ksh"
EOF

Note that you can't easily check the shell you are in by echo $SHELL, because the parent shell expands this variable to the text /././bash. If you want to be sure that the child shell works, you should check if a shell-specific syntax is working or not.

Upvotes: 3

hek2mgl
hek2mgl

Reputation: 158280

You need to use the -c command line option if you want to pass commands on bash startup:

#!/bin/bash
# We are in bash already ...
echo $SHELL

csh -c 'echo $SHELL'
ksh -c 'echo $SHELL'

Upvotes: 1

SAMdroid
SAMdroid

Reputation: 273

It is possible to use the command line options provided by each shell to run a snippet of code.

For example, for bash use the -c option:

bash -c $code
bash -c 'echo hello'

zsh and fish also use the -c option.

Other shells will state the options they use in their man pages.

Upvotes: 1

Related Questions