Ошибка too many arguments

If your $VARIABLE is a string containing spaces or other special characters, and single square brackets are used (which is a shortcut for the test command), then the string may be split out into multiple words. Each of these is treated as a separate argument.

So that one variable is split out into many arguments:

VARIABLE=$(/some/command);  
# returns "hello world"

if [ $VARIABLE == 0 ]; then
  # fails as if you wrote:
  # if [ hello world == 0 ]
fi 

The same will be true for any function call that puts down a string containing spaces or other special characters.


Easy fix

Wrap the variable output in double quotes, forcing it to stay as one string (therefore one argument). For example,

VARIABLE=$(/some/command);
if [ "$VARIABLE" == 0 ]; then
  # some action
fi 

Simple as that. But skip to «Also beware…» below if you also can’t guarantee your variable won’t be an empty string, or a string that contains nothing but whitespace.


Or, an alternate fix is to use double square brackets (which is a shortcut for the new test command).

This exists only in bash (and apparently korn and zsh) however, and so may not be compatible with default shells called by /bin/sh etc.

This means on some systems, it might work from the console but not when called elsewhere, like from cron, depending on how everything is configured.

It would look like this:

VARIABLE=$(/some/command);
if [[ $VARIABLE == 0 ]]; then
  # some action
fi 

If your command contains double square brackets like this and you get errors in logs but it works from the console, try swapping out the [[ for an alternative suggested here, or, ensure that whatever runs your script uses a shell that supports [[ aka new test.


Also beware of the [: unary operator expected error

If you’re seeing the «too many arguments» error, chances are you’re getting a string from a function with unpredictable output. If it’s also possible to get an empty string (or all whitespace string), this would be treated as zero arguments even with the above «quick fix», and would fail with [: unary operator expected

It’s the same ‘gotcha’ if you’re used to other languages — you don’t expect the contents of a variable to be effectively printed into the code like this before it is evaluated.

Here’s an example that prevents both the [: too many arguments and the [: unary operator expected errors: replacing the output with a default value if it is empty (in this example, 0), with double quotes wrapped around the whole thing:

VARIABLE=$(/some/command);
if [ "${VARIABLE:-0}" == 0 ]; then
  # some action
fi 

(here, the action will happen if $VARIABLE is 0, or empty. Naturally, you should change the 0 (the default value) to a different default value if different behaviour is wanted)


Final note: Since [ is a shortcut for test, all the above is also true for the error test: too many arguments (and also test: unary operator expected)

Solve cd: Too Many Arguments Error in Bash

We use the cd command to change the working directory in Linux. However, incorrect use of this command may cause an error.

This article will explain how to solve the bash: cd: too many arguments error in Linux Bash.

Solve bash: cd: too many arguments Error in Bash

The cd command accepts a directory name as an argument and replaces the current shell environment’s working directory with the given directory.

If no argument is given, the cd command behaves as if the directory named in the HOME environment variable was specified as the argument.

If the directory you want to go to consists of more than one word and contains spaces, you should not give it an argument directly. The command below will generate the bash: cd: too many arguments error.

The command accepts test and directory as separate arguments and cannot operate. To solve this problem, you must write the directory name in quotation marks; use single or double quotes as you wish.

The following command will run without error, and the current directory will be replaced with the test directory. Using a slash (/) after the directory name is optional.

Another way to do this is to use the backslash character. The backslash () is an escape character, and it preserves the literal value of the next character that follows.

So you can use the space character.

The following command will also run without error, and the current directory will be replaced with the test directory. Using a slash (/) after the directory name is optional.

Background

Ran into a little error using “”Git Bash” on MS Windows.

Error Message – fatal: Too many arguments.

Image

Text

$ sh gitCloneShare.sh
+ IFS='$’nt’'
+ repository_=https://github.com/DanielAdeniji/sampleWork
+ folder_=sampleWork2
+ git clone h '' ps://gi hub.com/Da ielAde iji/sampleWork sampleWork2
fatal: Too many arguments.

Code

#!/bin/bash

set -x

IFS=$’nt’

repository_="https://github.com/DanielAdeniji/sampleWork"

folder_="sampleWork2"

git clone $repository_ $folder_

TroubleShooting

Outline

  1. Show Hidden Characters
    • Linux / GitBash
      • vi
        • show hidden characters
    • MS Windows
      • Notepad++
        • show hidden characters

Task

Git Bash

vi
Show Hidden Characters
Outline
  1. Original Plain text view
  2. Enter Command Mode and type “set list
  3. Hidden text is shown
Image – Before

Image – Transition to Showing Hidden Characters

Image – Show Hidden Characters

Explanation
  1. Nothing stands out

MS Windows

notepad++
Show Hidden Characters
Outline
  1. Original Plain text view
  2. Using menu access:- View / Show Symbol / Show All Characters
  3. Hidden text is shown
Image – Before
Image – Show Hidden Characters

Explanation
  1. Nothing stands out

Remediation

Outline

  1. IFS (  Internal Field Separator )
    • Discard
    • Replace
      • Original:- IFS=$nt
      • Revised:- IFS=$nt

Task

IFS (  Internal Field Separator )

Discard

In our particular use-case, we do not need to override the IFS.

And, so we are very well served if we just discard it.

Replace

For those who believe in preserving code copied from elsewhere, please use it well.

original

revised

Explanation

Please make sure that you use proper quotes.

In this case, single quotes (‘) or double-quotes will suffice.

References

  1. Chrispian H. Burks
    • Quick vi tip: Show Hidden Characters
      Link

I’m trying to create a directory and cd into it:

In ~/.bashrc:

function abc() {
  appname=$1
  appdir="$HOME/code/$appname"
  if [ mkdir $appdir -a cd $appdir ]; then
    echo Success
  else
    echo Failed to create and switch directory
  fi
}

When I reload bashrc (. ~/.bashrc) I get the error:

bash: [: too many arguments
Failed to create and switch directory

How do I fix this? And what does [: in the error mean?

Ps. Could someone direct me to a «non-cryptic» bash scripting tutorial?

Community's user avatar

asked May 2, 2011 at 2:16

Zabba's user avatar

2

The main error in your script is that the [ command, equivalent to test command, is used to test conditions, like string comparison, existence of files, and so on.

To test the exit status of processes you have to use if without [, so your script could be

if mkdir "$appdir" && cd "$appdir"; then
  echo "Success"
else
  echo "Failed to create and switch directory"
fi

This is explained in Bash Pitfalls: 9. if [grep foo myfile.

I suggest you go through GrayCat Bash Guide to understand bash.

answered May 2, 2011 at 7:17

enzotib's user avatar

enzotibenzotib

91.5k11 gold badges164 silver badges177 bronze badges

2

A prototype could be:

  • Create a file in your desktop: touch newDirectory.sh
  • Make file executable: chmod +x newDirectory.sh
  • To call the script from a terminal in the desktop : ./newDirectory.sh anyName

/

#!/bin/bash
function abc() {
  appname=${1}
  appdir="$HOME/Desktop/$appname"
  if (( mkdir "${appdir}" )) ; then     
    cd "${appdir}"  
    echo "Success" 
  else   
    echo "Failed to create and switch directory" 
  fi
}
abc ${1}

Little recommendation: if you are new, do not mess with .bashrc :)

enzotib's user avatar

enzotib

91.5k11 gold badges164 silver badges177 bronze badges

answered May 2, 2011 at 3:45

studentz's user avatar

9

To fully understand why you’re seeing this error, you have to first understand what a function is and how it works.

Basics of a function

A function is a block of code which can do any repetitive task. It can be run any number of times and anywhere in the project without repeating identical code over and over again.

For example, you may want to develop a function to:

  1. Format an Excel sheet based on some conditions
  2. Use or display user information
  3. Perform mathematical calculations

By facilitating code reuse, functions make your code free from redundancy  and also cut down the maintenance overhead. There is no need to make changes to the same code in several different areas. Instead, the function can be enhanced / updated as required. It saves time and effort and keeps your code organized.

Parameters in a Function

The input data that may be required for any action the function does is passed into the function in the form of parameters or arguments. Functions can also return some value after performing an action. Such a value is called a return value.

Syntax for arguments:

Function <Function name> ([argument1 [, argument2 [, argument3 [ …… ] ] ] ] ])

<function code>

End Function

For example:

This function prints whether the customer is a senior citizen or not by just validating the customer’s age — which is passed to the function as an argument. In the sub procedure below, this function is called by passing the age value received from the user as an input argument.

'called function
Function typeofcustomer(age)
    If age &amp;amp;gt; 60 Then
        Debug.Print "Customer is a senior citizen"
    Else
        Debug.Print "Customer is not a senior citizen"
    End If

End Function
Sub findout()
    custage = InputBox("Enter the age of the customer")
'calling function
    typeofcustomer (custage)
End Sub

Built-in functions

Built-in functions are readymade functions predefined and offered by the programming language. They can be widely used in our code to made it work efficiently.

VBA Built-in Functions

The following are some built-in functions offered by VBA

S.no Function name Description Syntax Example Output of the example
1 Lcase() Converts the word in the argument into a lowercase word and returns it Lcase (<string>) Lcase(“ApplE”) “apple”
2 Trim() Removes the leading and trailing spaces of the argument Trim (<string>) Trim(”  Santa Claus  “) “Santa Claus”
3 IsDate() This function returns a boolean value to state if te string passed as an argument in a valid Date IsDate (<string>) IsDate( “20-11-2020” ) TRUE
4 CurDir() This funciton returns the path in which the current file resides. CurDir CurDir “C:UsersJANANIDocuments”

MS Excel Built-in Functions

Similarly, Microsoft Excel ( the host application) also facilitates the users with a wide range of in-built functions. Some of those are furnished below.

  1. If
  2. Vlookup
  3. Hlookup
  4. Count
  5. Countif
  6. Sum
  7. Sumif
  8. Average
  9. Trim
  10. Min
  11. Max
  12. And
  13. Or
  14. Not
  15. Iferror
  16. Xor

To see the functions and their descriptions directly in Excel , you can select a cell and click on the “fx” symbol as shown in the image below. This will open up a dialog with a list of functions under each category to choose from. Depending on what you’re trying to do, a function can be chosen and used.

Select the category to see the list of functions under it.

Common causes for the error

Very often, you’ll find that typos are the cause of the error “You’ve entered too many arguments.”

In the above list, there are several functions which can be nested and used in conjunction with one another.

For example, the syntax for If function is

IF( condition1, <what is to be done or displayed if condition is true>,<what is to be done or displayed if condition is false>)

Now this can lead to a nested if condition if another condition needs to be tested in the place of the second or third parameter.

Scenario:

  1. Here is a formula with nested if conditions to calculate tax amount for salaries.

If any of the brackets or commas as not closed, i.e not as per the syntax requirements, we get the error below.

If we add unnecessary arguments accidentally, we see the same error again.

  • For the scenario, we are trying to find the total marks of a specific student using the Vlookup formula.

In this case, we have provided an extra argument by mistake and the error below shows up.

Solution

So to fix the error “You’ve entered too many arguments for this function” you need to go through the content of the cell, character-by-character, to ensure that there are no syntax errors. In other words, you need to check whether all opened brackets are closed and all commas are properly in place. Also, the number of arguments you provide has to match the function’s syntax.

Note: Functions like Average, Sum, Min and Max have no limitations in the number of arguments.

But what about in VBA?

If we try to write the same formula in Excel using VBA, the code looks like the example below. It also works well.

Sub arg_error()

' select a cell in which the formula needs to be inserted
    Range("B3").Select

' insert the formula in the cell
    ActiveCell.FormulaR1C1 = _
        "=IF(RC[-1]&amp;amp;gt;250000,IF(RC[-1]&amp;amp;lt;700000,(RC[-1]* 10)/100,""to be calculated later""),""0"")"

End Sub

But if similar mistakes are made in this VBA code — i.e omission of a parentheses, or of a comma, or the existence of an additional parameter, the error that is thrown is actually very generic. This might confuse the user.

You end up getting the more generic “Run-time error ‘1004’: Application-defined or object defined error.”

Conclusion:

The error “You’ve entered too many arguments for this function” is not specific to the “If” condition or function in MS. Excel. It can be thrown when the syntax is incomplete for any of the in-built functions used in Excel.

A tip to avoid this kind of typo and careless error

When you open a bracket to insert a new condition or data, it is better to close the bracket before inserting that data. So as soon as you type a “(“ , you should immediate type a “)” and then move the cursor between these brackets to insert the required data. This can avoid syntax errors that eat up your time.

See also:

For a very closely related error, read the article Argument Not Optional.

Понравилась статья? Поделить с друзьями:
  • Ошибка too few arguments to function
  • Ошибка tom clancy s rainbow six siege
  • Ошибка token expired
  • Ошибка to run this application
  • Ошибка tire pressure low