(C) 2003-2009 By Yamauchi, Hitoshi --> sh (bash)

Sh scripts (bash)


function with argments

bash can make a function with arguments. The behavior of arguments is the same to the command line arguments. (I do not know how to make a user defined functions in csh.)

------------------------------
#! /bin/bash
function foo ()
{
    for i in $*
    do
	echo $i
    done
}
foo this is a test
------------------------------

unset an option

There are many options you can set/unset.


Parameter Expansion: The difference between Use and Assign

I took a bit time to understand the Parameter Expansion: Use and Assign. When you get once, it is clear and obvious.

------------------------------
#! /bin/bash
defaultval="This is default."
echo "${val:-$defaultval}, \${val} = ${val}"
echo "${val:=$defaultval}, \${val} = ${val}"
------------------------------

The results are the next.

------------------------------
This is default., ${val} =
This is default., ${val} = This is default.
------------------------------

So, `use' uses values only one time, but the value is not assigned. If the variable (= val) is unset or null, the variable (= val) is still unset or null after ${val:-$defaultval}. Instead of this, ${val:=$defaultval} assign the $defaultval to val.


How to check a variable is defined or not?

My first shell was csh. However, I usually write a sh-script by (ba)sh, since mainly tcsh is hard for me around some issue of file descriptor, quote, signal handling, user defined functions and so forth. But how can I do in sh of ${?name} in csh?

It seems sh does not so much care the difference of unset or null. Then I should care about the style, a condition variable should have value and if no value, it should be treated as undefined. (or other way around but should be consistent.)

------------------------------
#! /bin/tcsh
if (${?SOME_DEBUG}) then
    setenv SOME_THREADS 1
endif
------------------------------
#! /bin/bash
if [ ${TMK_DEBUG:-"nondefined"} != "nondefined" ]; then
    export TMK_THREADS=1
fi
------------------------------

Black Magic

How to create (almost) empty environment on bash?


Copyright (C) 2003-2009 Yamauchi, Hitoshi
Most recent update : :