0

I am just starting out with shell scripting (sh), and I have two issues.

Issue 1: I'm trying to make a very simple script that creates a directory and immediately goes into it. This is the script I currently have:

#!/bin/sh
mkdir -p "$1"
cd "$1"

For some reason, this does not work. It creates the directory, but does not go into it. Am I missing something obvious here?

Issue 2: I'm writing a very simple calculator that uses expr. But for the multiplication, I use x instead of *. So this is what I have right now:

#!/bin/sh

if test $# -lt 3
then
   echo "Usage calc [operand1] [operator] [operand2]"
   exit
fi

if test $2 = x
then
   op='\*'
else
   op=$2
fi

ret=`expr $1 $op $3`
echo $ret

This works for all the operations except multiplication. Calling calc 100 x 10, for example, gives a syntax error. I tried different combinations, but I can't seem to get the right way of assigning \* to op. What's the right way of doing it?

1 Answer 1

1

a) the script is run in a new shell. The cd doesn't apply to the outer. Try a shell alias instead of this script.

b) Quote parameters differently, in particular in expr

Sign up to request clarification or add additional context in comments.

1 Comment

An alias wouldn't be any good, because you need to reuse the same argument twice. A shell function would work though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.