sh[it] and What am I missing here?

David Christensen dpchrist at holgerdanske.com
Sun Jun 5 21:00:43 UTC 2016


On 06/05/2016 10:15 AM, Baho Utot wrote:
> I only want to create a script ( sh script ) and run if from a clean
> machine with just base install nothing else and then run my sh script to
> build some ports.  That's were the trouble lies.  ie functions not
> returning status for example:
>
> test.sh
> chmod +x test.sh
>
> #!/bin/sh
>
> func() {
>      echo "Yep it's me"
>      return 1
> }
>
> if [ func ] ; then                 # if [ 1 = func ] or if [ 1 -eq func
> ] doesn't work either
>      echo "This works"
> fi
>
> ./test.sh
>
> [: func: unexpected operator

If I run your code on my FreeBSD 10.1 box with Csh login shell:

	dpchrist at p42800e:~/sandbox/sh % uname -a
	FreeBSD p42800e 10.1-RELEASE-p35 FreeBSD 10.1-RELEASE-p35 #0: Sat May 
28 03:02:45 UTC 2016 
root at amd64-builder.daemonology.net:/usr/obj/usr/src/sys/GENERIC  i386
	dpchrist at p42800e:~/sandbox/sh % echo $SHELL
	/bin/csh
	dpchrist at p42800e:~/sandbox/sh % cat baho-utot.sh
	#!/bin/sh

	func() {
	    echo "Yep it's me"
	    return 1
	}

	if [ func ] ; then                 # if [ 1 = func ] or if [ 1 -eq func 
] doesn't work either
	    echo "This works"
	fi
	dpchrist at p42800e:~/sandbox/sh % ./baho-utot.sh
	This works


I do not see the string "Yep it's me".


I see the string "This works".


I do not see an error message.


I get the same results if I change my login shell to Sh:

	$ echo $SHELL
	/bin/sh
	$ ./baho-utot.sh
	This works


Enabling the -v and -x options for Sh provides a clue -- 'func' is not 
getting called:

	$ echo $SHELL
	/bin/sh
	$ /bin/sh -v -x baho-utot.sh
	#!/bin/sh

	func() {
	    echo "Yep it's me"
	    return 1
	}

	if [ func ] ; then                 # if [ 1 = func ] or if [ 1 -eq func 
] doesn't work either
	    echo "This works"
	fi
	+ [ func ]
	+ echo 'This works'
	This works


Calling 'func' and then testing '$?' (exit value special variable) 
explicitly seems to help:

	$ cat baho-utot-2.sh
	#!/bin/sh

	func() {
	    echo "func returning 1"
	    return 1
	}

	func2() {
	    echo "func2 returning 0"
	    return 0
	}

	func
	if [ $? = 1 ] ; then
	    echo "func worked"
	else
	    echo "func did not work"
	fi

	func2
	if [ $? = 1 ] ; then
	    echo "func2 worked"
	else
	    echo "func2 did not work"
	fi
	$ ./baho-utot-2.sh
	func returning 1
	func worked
	func2 returning 0
	func2 did not work


David



More information about the freebsd-questions mailing list