I have 2 variables


and I have one Directory in my system /opt/web/C70/MBA/

How can I go to this directory using variables

for example cd /opt/web/$VAL1/$VAL2

How can I extract the particular text from variable in shell script?


The answer of @Anthon is perfectly correct, though it implies a bit too much typing IMO. I suggest defining a shell (bash) function named (eg.) "mycd" as a wrapper:

function mycd {
  cd /opt/web/${VAL1:0:3}/${VAL2:0:3}

Now, no matter whatever values the variables $VAR1 and $VAR1 currently have, calling this function will change directory to the expected location.

Try the following example in a running bash terminal, hitting ENTER at the end of each input line window):

user% cd; pwd
user% function mycd { cd /opt/web/${VAL1:0:3}/${VAL2:0:3} }
user% export VAL1="C70AN"; export VAL2="MBA30"
user% mycd
user% pwd

This example of course requires the existence of the directory tree "/opt/web/C70/MBA" to work. If this ist not the case, you will receive an error message like

bash: cd: /opt/web/C70/MBA: file or directory not found

This result is still a prove for the correct work of the "mycd" function as it tries to change to the calculated directory - which does not (yet) exist.

HTH, too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.