*NIX Tricks

[csh] Simple loops in csh or tcsh

Posted in csh by kousik on March 3, 2011

If you are stuck with a c-shell and you want to print (or execute a command) for an increment, say of 5,  in a variable (for example, $x), then do either of the following:

#!/bin/csh
# Exammple: 1
foreach x (`seq 1 5 20`)
     echo $x
end
#EOF

#!/bin/csh
# Example: 2
@ x = 1
while ($x <= 20)
     echo $x
@ x += 5
end
#EOF

They both print the numbers 1 to 20 in steps of 5. If you want to use it in the command line, then you need to type each line (of course, except  #!/bin/csh and #EOF) and hit enter .

If you know all the possible elements (numbers, characters or strings) of the array passed on to x for each foreach, then you may  choose to use the following

#!/bin/csh
# Example: 3
foreach x (1 2 9 40)
     echo $x
end
#EOF

when the elements are 1, 2, 9 and 40; or

#!/bin/csh
# Example: 4
foreach x (*.cpp)
     echo $x
end
#EOF

when the elements are all the filenames ending with .cpp in the current directory.

Update: The second option (Example: 2) spits out some syntax error message when used in the command line (in the same way as mentioned above). However, it works fine in a script file.

Tagged with: , , , ,

[cli] Find out success status of a command in BASH/ CSH

Posted in bash, cli, csh by kousik on November 20, 2009

To know the return value of a command, in BASH run
$ echo $?
and in CSH/ TCSH run
$ echo $status
which will give you the return value (0 or 1) of the last command (the one issued just before the echo).

In both the shells, if the above spits out 0 (zero), it means the previous command was successfully completed, otherwise it’ll give rise to 1 (unsuccessful!) — quite contrary to our concept of 0 being false and 1 being true, eh!

Credit: Oracle Spin.

[unix] Change default login shell

Posted in unix by kousik on October 26, 2009

I just stumbled upon a few ways to change the default login shell to bash:

The easiest one is

$ chsh -s /bin/bash username

On some machines you may have to use ypcsh instead of chsh. The full path of the shell executable must be specified.

But if you have root access you may have the option to use either of the following two as well:

  • $ usermod -s bash username
  • Change it by editing the entry for the user in /etc/passwd file, manually.

If none of the above works, here’s a workaround!

N.B. Make sure that the desired shell is listed in /etc/shells file.

Follow

Get every new post delivered to your Inbox.