Solutions to the problem of too many arguments in Linux Bash

This paper introduces the solution to the problem of too many arguments in Linux bash shell, which can be referred to by friends in need

Transferred from:

http://www.jbxue.com/article/13378.html

To determine whether the content of a file is empty, use the following statement:

if test -z `cat filename`

When the file name is empty or there is only one line of string without spaces, everything is normal. Otherwise, it will report errors such as: too many arguments, or even: binary operator expected.

Reference article: http://www.ibm.com/developerworks/cn/linux/shell/bash/bash-2/index.html

Cause analysis:

Bash is confused by the space carriage return in the file name.

If the environment variables are not in double quotes, bash thinks there are too many arguments in the condition.

You can eliminate this problem by enclosing string arguments in double quotation marks.

It seems that to develop the habit of enclosing all string arguments in double quotation marks will eliminate many similar programming errors.

Solution:

Add double quotation marks to the command execution part

if test -z “`cat filename`”

The second solution of shell’s too many arguments is as follows:

Today, due to solving a small problem occasionally, we encounter a strange problem, the different effects of “[]” and “[]]”, which are summarized as follows

Show code: if [- Z ` lsof – I: 22 ‘]// this writing method will report too many arguments and change to [[- Z ` lsof – I: 22’]]

then

echo “the port is not running”

else

echo “the port is running”

fi

When you run this simple shell script, you always report too many arguments, and finally find out that it has something to do with the universality of the version. More simply, “[]]” has better universality than “[]”. Therefore, in order to avoid this problem, you can directly replace “[]” with “[]]”. Moreover, “[]” has stronger fault tolerance than “[]”, that is, the error that may be reported in “[]” may not be reported in “[]] structure, such as & amp& amp;,|| This kind of logical judgment, because it is not the focus of this article, is passed by.

Similar Posts: