最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Why does this bash script fail on ubuntu? - Stack Overflow

programmeradmin1浏览0评论

On ubuntu I run the following script (which should randomly fail or succeed for testing purposes):

if [ "$RANDOM" -gt 16384 ]; then
    echo "Success!"
    exit 0
else
    echo "Failure!"
    exit 1
fi

with

sh random.sh

but it fails with

random.sh: 1: [: Illegal number: 
Failure!

What is the cause of the problem?

On ubuntu I run the following script (which should randomly fail or succeed for testing purposes):

if [ "$RANDOM" -gt 16384 ]; then
    echo "Success!"
    exit 0
else
    echo "Failure!"
    exit 1
fi

with

sh random.sh

but it fails with

random.sh: 1: [: Illegal number: 
Failure!

What is the cause of the problem?

Share Improve this question asked Mar 28 at 9:55 AlexAlex 44.5k104 gold badges300 silver badges513 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 5

The $RANDOM variable is a bash extension, so you have to invoke your script with bash instead of sh. On Ubuntu, sh is typically linked to the more light-weight dash shell which doesn't support these extensions.

Also see Difference between sh and Bash

To make reasonably sure that the correct interpreter is used, add a shebang to your script:

#!/bin/bash

if [ "$RANDOM" -gt 16384 ]; then
    echo "Success!"
    exit 0
else
    echo "Failure!"
    exit 1
fi

and make it executable:

chmod +x random.sh

A user can now simply execute the script without specifying what interpreter it needs in order to work properly:

./random.sh
发布评论

评论列表(0)

  1. 暂无评论