Setting an environment variable in csh

无人久伴 提交于 2019-12-11 06:39:45

问题


I have the following line at the first line in my script file:

#!/bin/sh

So I'm using csh.(?)

I wanto assign the output of the following to an environment variable:

echo $MYUSR | awk '{print substr($0,4)}'

I try:

set $MYVAR = echo $MYUSR | awk '{print substr($0,4)}'

But it doesn't work, How can I do it? I want to do it in a sh file.


回答1:


Your script should look like

 #!/bin/csh

 set MYVAR = `echo $MYUSR | awk '{print substr($0,4)}'`

 echo $MYVAR

I don't have a way to test this right now, let me now if it doesn't work.


If you've inherited the basis of your script from someone else, with the #!/bin/sh, then you have to find out if /bin/sh is really the bourne shell, or if it is a link to /bin/bash

You can tell that by doing

   ls -l /bin/sh /bin/bash

if you get back information on files where the size is exactly the same, the you're really using bash, but called as /bin/sh

So try these 2 solutions

   MYVAR=$(echo $MYUSR | awk '{print substr($0,4)}')
   echo $MYVAR

AND

   MYVAR=``echo $MYUSR | awk '{print substr($0,4)}``  
   echo $MYVAR

   # arg!! only one pair of enclosing back-ticks needed, 
   # can't find the secret escape codes to make this look exactly right.

in all cases (csh) included, the back-ticks AND the $( ... ) are known as command substitution. What every output comes from running the command inside, is substituted into the command line AND then the whole command is executed.

I hope this helps.




回答2:


if it's /bin/sh it's bourne shell or bash, and use back quotes to execute something and this to assign that...

MYVAR=`echo $MYUSR | awk ...`



回答3:


That script first line indicates that it should be interpreted by the Bourne shell (sh), not csh. Change it to

#!/bin/csh



回答4:


The first line of your code shows clearly you are not using a csh. You are using a plain sh environment/shell. You have 2 options:

  1. Either change the first line to #!/bin/csh OR
  2. Keeping first line unchanged, update the code for setting the variable.

    MYVAR=`echo $MYUSR | awk '{print substr($0,4)}`
    echo $MYVAR
    

Let me know, if you get any error.



来源:https://stackoverflow.com/questions/9739516/setting-an-environment-variable-in-csh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!