Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Attempted assignment to non-variable (error token is "= 0 ")

Very new to this and pulling my hair out over here. Help is appreciated. Here's my error:

Here's my script-

Zanna's user avatar

Inside (( ... )) arithmetic evaluation, = is an assignment operator not a logical comparison operator. So $(($w = 0)) is dereferencing variable w , and then attempting to assign the value 0 to its value .

Probably what you intended was if $(($w == 0)) . However - although syntactically correct - the parameter expansion syntax $w is not necessary in this context so you could simplify that to if ((w == 0)) , and similarly for $(( $w != 0 )) and so on. From the ARITHMETIC EVALUATION section of man bash :

Shell variables are allowed as operands; parameter expansion is per‐ formed before the expression is evaluated. Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax.

Also note that -le , -gt operators are for arithmetical comparison within [ ... ] or [[ ... ]] test brackets; within (( ... )) brackets (which are for arithmetic evaluation only ), you should use <= , > and so on.

steeldriver's user avatar

  • I switched line 13 to $[ w== 0 ] (tried it with a $ before w as well) and it results in this message- /home/rdmorgan0001/bin/dfchkr1.sh: line 13: 0: command not found /home/rdmorgan0001/bin/dfchkr1.sh: line 18: 1: command not found /home/rdmorgan0001/bin/dfchkr1.sh: line 24: -ge 100 : syntax error in expression (error token is "100 ") –  morgro269 Commented May 14, 2017 at 12:20
  • The $[ . . . ] form of arithmetic evaluation is deprecated and should not be used in new code - see for example stackoverflow.com/a/2415777/4440445 –  steeldriver Commented May 14, 2017 at 13:30

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged bash ..

  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Announcing a change to the data-dump process

Hot Network Questions

  • What is the translation of the word "ibn" that some Rabbis have in their name?
  • Cannot get clear photos with 48 megapixel camera
  • How accurate is my phone's magnetometer?
  • Can "the" mean "enough"? — E.g.: "She will bake a pie, if she has the ingredients."
  • Why is transfer of heat very slow as compared to transfer of sound in solids?
  • Is conditional expectation evaluated by the copula strictly increasing when the correlation coefficient is positive and vice versa?
  • Boundedness of sum of sin(sin(n))
  • How much and how candid should my feedback be when leaving a team?
  • How to cover large patch of damp?
  • Private sector professional being screened out of PhD program
  • What's wrong with constructions like "Dragons are big, green, and eat people."?
  • Does space dust fall on the roof of my house and if so can I detect it with a cheap home microscope?
  • One Page IDP issued by Govt. Of India not acceptable in Japan
  • Why is There a Spelling Shift in the Stem of Verb "reperire"?
  • Can reflections of powerful gamma-ray bursts reveal normally undetectable distant objects in the solar system?
  • A novel where evolution from Neanderthals to us, and from us to superhumans is just by shedding facial skin to become less prognathous
  • How to play mono (or very unbalanced stereo) through both ears?
  • Determine the area of region satisfying the given condition
  • Why can't we prove SAT is NP complete just using the Tseytin Transformation?
  • A complex eight pieces endgame
  • Adjust size of symbol after rotation
  • Fantasy book series about a lord (and maybe a lady) who rules over a world where it's eternally spring, summer, fall, etc
  • A simple logic control yet it does not work
  • Passport Renewals

bash attempted assignment to non variable

How-To Geek

How to work with variables in bash.

4

Your changes have been saved

Email Is sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

8 Easy Home Assistant Automations to Make Your Life Easier

Using linux after windows is easier if you know these 6 key differences, these are the 5 most beautiful linux distros.

Hannah Stryker / How-To Geek

Quick Links

What is a variable in bash, examples of bash variables, how to use bash variables in scripts, how to use command line parameters in scripts, working with special variables, environment variables, how to export variables, how to quote variables, echo is your friend, key takeaways.

  • Variables are named symbols representing strings or numeric values. They are treated as their value when used in commands and expressions.
  • Variable names should be descriptive and cannot start with a number or contain spaces. They can start with an underscore and can have alphanumeric characters.
  • Variables can be used to store and reference values. The value of a variable can be changed, and it can be referenced by using the dollar sign $ before the variable name.

Variables are vital if you want to write scripts and understand what that code you're about to cut and paste from the web will do to your Linux computer. We'll get you started!

Variables are named symbols that represent either a string or numeric value. When you use them in commands and expressions, they are treated as if you had typed the value they hold instead of the name of the variable.

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore. Apart from that, you can use any mix of upper- and lowercase alphanumeric characters.

Here, we'll create five variables. The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.

We'll create four string variables and one numeric variable,

my_name=Dave

my_boost=Linux

his_boost=Spinach

this_year=2019

Defining variables in Linux.

To see the value held in a variable, use the echo command. You must precede the variable name with a dollar sign $ whenever you reference the value it contains, as shown below:

echo $my_name

echo $my_boost

echo $this_year

Using echo to display the values held in variables in a terminal window

Let's use all of our variables at once:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year"

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" in a terminal window

The values of the variables replace their names. You can also change the values of variables. To assign a new value to the variable, my_boost , you just repeat what you did when you assigned its first value, like so:

my_boost=Tequila

my_boost=Tequila in a terminal window

If you re-run the previous command, you now get a different result:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" in a terminalwindow

So, you can use the same command that references the same variables and get different results if you change the values held in the variables.

We'll talk about quoting variables later. For now, here are some things to remember:

  • A variable in single quotes ' is treated as a literal string, and not as a variable.
  • Variables in quotation marks " are treated as variables.
  • To get the value held in a variable, you have to provide the dollar sign $ .
  • A variable without the dollar sign $ only provides the name of the variable.

Correct an incorrect examples of referencing variables in a terminal window

You can also create a variable that takes its value from an existing variable or number of variables. The following command defines a new variable called drink_of_the_Year, and assigns it the combined values of the my_boost and this_year variables:

drink_of-the_Year="$my_boost $this_year"

echo drink_of_the-Year

drink_of-the_Year="$my_boost $this_year" in a terminal window

Scripts would be completely hamstrung without variables. Variables provide the flexibility that makes a script a general, rather than a specific, solution. To illustrate the difference, here's a script that counts the files in the /dev directory.

Type this into a text file, and then save it as fcnt.sh (for "file count"):

#!/bin/bashfolder_to_count=/devfile_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

Before you can run the script, you have to make it executable, as shown below:

chmod +x fcnt.sh

chmod +x fcnt.sh in a terminal window

Type the following to run the script:

./fcnt.sh in a terminal window

This prints the number of files in the /dev directory. Here's how it works:

  • A variable called folder_to_count is defined, and it's set to hold the string "/dev."
  • Another variable, called file_count , is defined. This variable takes its value from a command substitution. This is the command phrase between the parentheses $( ) . Note there's a dollar sign $ before the first parenthesis. This construct $( ) evaluates the commands within the parentheses, and then returns their final value. In this example, that value is assigned to the file_count variable. As far as the file_count variable is concerned, it's passed a value to hold; it isn't concerned with how the value was obtained.
  • The command evaluated in the command substitution performs an ls file listing on the directory in the folder_to_count variable, which has been set to "/dev." So, the script executes the command "ls /dev."
  • The output from this command is piped into the wc command. The -l (line count) option causes wc to count the number of lines in the output from the ls command. As each file is listed on a separate line, this is the count of files and subdirectories in the "/dev" directory. This value is assigned to the file_count variable.
  • The final line uses echo to output the result.

But this only works for the "/dev" directory. How can we make the script work with any directory? All it takes is one small change.

Many commands, such as ls and wc , take command line parameters. These provide information to the command, so it knows what you want it to do. If you want ls to work on your home directory and also to show hidden files , you can use the following command, where the tilde ~ and the -a (all) option are command line parameters:

Our scripts can accept command line parameters. They're referenced as $1 for the first parameter, $2 as the second, and so on, up to $9 for the ninth parameter. (Actually, there's a $0 , as well, but that's reserved to always hold the script.)

You can reference command line parameters in a script just as you would regular variables. Let's modify our script, as shown below, and save it with the new name fcnt2.sh :

#!/bin/bashfolder_to_count=$1file_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

This time, the folder_to_count variable is assigned the value of the first command line parameter, $1 .

The rest of the script works exactly as it did before. Rather than a specific solution, your script is now a general one. You can use it on any directory because it's not hardcoded to work only with "/dev."

Here's how you make the script executable:

chmod +x fcnt2.sh

chmod +x fcnt2.sh in a terminal window

Now, try it with a few directories. You can do "/dev" first to make sure you get the same result as before. Type the following:

./fnct2.sh /dev

./fnct2.sh /etc

./fnct2.sh /bin

./fnct2.sh /dev in a terminal window

You get the same result (207 files) as before for the "/dev" directory. This is encouraging, and you get directory-specific results for each of the other command line parameters.

To shorten the script, you could dispense with the variable, folder_to_count , altogether, and just reference $1 throughout, as follows:

#!/bin/bash file_count=$(ls $1 wc -l) echo $file_count files in $1

We mentioned $0 , which is always set to the filename of the script. This allows you to use the script to do things like print its name out correctly, even if it's renamed. This is useful in logging situations, in which you want to know the name of the process that added an entry.

The following are the other special preset variables:

  • $# : How many command line parameters were passed to the script.
  • $@ : All the command line parameters passed to the script.
  • $? : The exit status of the last process to run.
  • $$ : The Process ID (PID) of the current script.
  • $USER : The username of the user executing the script.
  • $HOSTNAME : The hostname of the computer running the script.
  • $SECONDS : The number of seconds the script has been running for.
  • $RANDOM : Returns a random number.
  • $LINENO : Returns the current line number of the script.

You want to see all of them in one script, don't you? You can! Save the following as a text file called, special.sh :

#!/bin/bashecho "There were $# command line parameters"echo "They are: $@"echo "Parameter 1 is: $1"echo "The script is called: $0"# any old process so that we can report on the exit statuspwdecho "pwd returned $?"echo "This script has Process ID $$"echo "The script was started by $USER"echo "It is running on $HOSTNAME"sleep 3echo "It has been running for $SECONDS seconds"echo "Random number: $RANDOM"echo "This is line number $LINENO of the script"

Type the following to make it executable:

chmod +x special.sh

fig13 in a terminal window

Now, you can run it with a bunch of different command line parameters, as shown below.

./special.sh alpha bravo charlie 56 2048 Thursday in a terminal window

Bash uses environment variables to define and record the properties of the environment it creates when it launches. These hold information Bash can readily access, such as your username, locale, the number of commands your history file can hold, your default editor, and lots more.

To see the active environment variables in your Bash session, use this command:

env | less in a terminal window

If you scroll through the list, you might find some that would be useful to reference in your scripts.

List of environment variables in less in a terminal window

When a script runs, it's in its own process, and the variables it uses cannot be seen outside of that process. If you want to share a variable with another script that your script launches, you have to export that variable. We'll show you how to this with two scripts.

First, save the following with the filename script_one.sh :

#!/bin/bashfirst_var=alphasecond_var=bravo# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"export first_varexport second_var./script_two.sh# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This creates two variables, first_var and second_var , and it assigns some values. It prints these to the terminal window, exports the variables, and calls script_two.sh . When script_two.sh terminates, and process flow returns to this script, it again prints the variables to the terminal window. Then, you can see if they changed.

The second script we'll use is script_two.sh . This is the script that script_one.sh calls. Type the following:

#!/bin/bash# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"# set new valuesfirst_var=charliesecond_var=delta# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This second script prints the values of the two variables, assigns new values to them, and then prints them again.

To run these scripts, you have to type the following to make them executable:

chmod +x script_one.shchmod +x script_two.sh

chmod +x script_one.sh in a terminal window

And now, type the following to launch script_one.sh :

./script_one.sh

./script_one.sh in a terminal window

This is what the output tells us:

  • script_one.sh prints the values of the variables, which are alpha and bravo.
  • script_two.sh prints the values of the variables (alpha and bravo) as it received them.
  • script_two.sh changes them to charlie and delta.
  • script_one.sh prints the values of the variables, which are still alpha and bravo.

What happens in the second script, stays in the second script. It's like copies of the variables are sent to the second script, but they're discarded when that script exits. The original variables in the first script aren't altered by anything that happens to the copies of them in the second.

You might have noticed that when scripts reference variables, they're in quotation marks " . This allows variables to be referenced correctly, so their values are used when the line is executed in the script.

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter.

Here's an example:

site_name=How-To Geek

site_name=How-To Geek in a terminal window

Bash sees the space before "Geek" as an indication that a new command is starting. It reports that there is no such command, and abandons the line. echo shows us that the site_name variable holds nothing — not even the "How-To" text.

Try that again with quotation marks around the value, as shown below:

site_name="How-To Geek"

site_name="How-To Geek" in a terminal window

This time, it's recognized as a single value and assigned correctly to the site_name variable.

It can take some time to get used to command substitution, quoting variables, and remembering when to include the dollar sign.

Before you hit Enter and execute a line of Bash commands, try it with echo in front of it. This way, you can make sure what's going to happen is what you want. You can also catch any mistakes you might have made in the syntax.

Linux Commands

Files

Processes

Networking

  • Linux & macOS Terminal

LinuxSimply

Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment > How to Assign Variable in Bash Script? [8 Practical Cases]

How to Assign Variable in Bash Script? [8 Practical Cases]

Mohammad Shah Miran

Variables allow you to store and manipulate data within your script, making it easier to organize and access information. In Bash scripts , variable assignment follows a straightforward syntax, but it offers a range of options and features that can enhance the flexibility and functionality of your scripts. In this article, I will discuss modes to assign variable in the Bash script . As the Bash script offers a range of methods for assigning variables, I will thoroughly delve into each one.

Table of Contents

Key Takeaways

  • Getting Familiar With Different Types Of Variables.
  • Learning how to assign single or multiple bash variables.
  • Understanding the arithmetic operation in Bash Scripting.

Free Downloads

Local vs global variable assignment.

In programming, variables are used to store and manipulate data. There are two main types of variable assignments: local and global .

A. Local Variable Assignment

In programming, a local variable assignment refers to the process of declaring and assigning a variable within a specific scope, such as a function or a block of code. Local variables are temporary and have limited visibility, meaning they can only be accessed within the scope in which they are defined.

Here are some key characteristics of local variable assignment:

  • Local variables in bash are created within a function or a block of code.
  • By default, variables declared within a function are local to that function.
  • They are not accessible outside the function or block in which they are defined.
  • Local variables typically store temporary or intermediate values within a specific context.

Here is an example in Bash script.

In this example, the variable x is a local variable within the scope of the my_function function. It can be accessed and used within the function, but accessing it outside the function will result in an error because the variable is not defined in the outer scope.

B. Global Variable Assignment

In Bash scripting, global variables are accessible throughout the entire script, regardless of the scope in which they are declared. Global variables can be accessed and modified from any script part, including within functions.

Here are some key characteristics of global variable assignment:

  • Global variables in bash are declared outside of any function or block.
  • They are accessible throughout the entire script.
  • Any variable declared outside of a function or block is considered global by default.
  • Global variables can be accessed and modified from any script part, including within functions.

Here is an example in Bash script given in the context of a global variable .

It’s important to note that in bash, variable assignment without the local keyword within a function will create a global variable even if there is a global variable with the same name. To ensure local scope within a function , using the local keyword explicitly is recommended.

Additionally, it’s worth mentioning that subprocesses spawned by a bash script, such as commands executed with $(…) or backticks , create their own separate environments, and variables assigned within those subprocesses are not accessible in the parent script .

8 Different Cases to Assign Variables in Bash Script

In Bash scripting , there are various cases or scenarios in which you may need to assign variables. Here are some common cases I have described below. These examples cover various scenarios, such as assigning single variables , multiple variable assignments in a single line , extracting values from command-line arguments , obtaining input from the user , utilizing environmental variables, etc . So let’s start.

Case 01: Single Variable Assignment

To assign a value to a single variable in Bash script , you can use the following syntax:

However, replace the variable with the name of the variable you want to assign, and the value with the desired value you want to assign to that variable.

To assign a single value to a variable in Bash , you can go in the following manner:

Steps to Follow >

❶ At first, launch an Ubuntu Terminal .

❷ Write the following command to open a file in Nano :

  • nano : Opens a file in the Nano text editor.
  • single_variable.sh : Name of the file.

❸ Copy the script mentioned below:

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Next, variable var_int contains an integer value of 23 and displays with the echo command .

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❺ Use the following command to make the file executable :

  • chmod : changes the permissions of files and directories.
  • u+x : Here, u refers to the “ user ” or the owner of the file and +x specifies the permission being added, in this case, the “ execute ” permission. When u+x is added to the file permissions, it grants the user ( owner ) permission to execute ( run ) the file.
  • single_variable.sh : File name to which the permissions are being applied.

❻ Run the script by using the following command:

Single Variable Assignment

Case 02: Multi-Variable Assignment in a Single Line of a Bash Script

Multi-variable assignment in a single line is a concise and efficient way of assigning values to multiple variables simultaneously in Bash scripts . This method helps reduce the number of lines of code and can enhance readability in certain scenarios. Here’s an example of a multi-variable assignment in a single line.

You can follow the steps of Case 01 , to save & make the script executable.

Script (multi_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Then, three variables x , y , and z are assigned values 1 , 2 , and 3 , respectively. The echo statements are used to print the values of each variable. Following that, two variables var1 and var2 are assigned values “ Hello ” and “ World “, respectively. The semicolon (;) separates the assignment statements within a single line. The echo statement prints the values of both variables with a space in between. Lastly, the read command is used to assign values to var3 and var4. The <<< syntax is known as a here-string , which allows the string “ Hello LinuxSimply ” to be passed as input to the read command . The input string is split into words, and the first word is assigned to var3 , while the remaining words are assigned to var4 . Finally, the echo statement displays the values of both variables.

Multi-Variable Assignment in a Single Line of a Bash Script

Case 03: Assigning Variables From Command-Line Arguments

In Bash , you can assign variables from command-line arguments using special variables known as positional parameters . Here is a sample code demonstrated below.

Script (var_as_argument.sh) >

Assigning Variables from Command-Line Arguments

Case 04: Assign Value From Environmental Bash Variable

In Bash , you can also assign the value of an Environmental Variable to a variable. To accomplish the task you can use the following syntax :

However, make sure to replace ENV_VARIABLE_NAME with the actual name of the environment variable you want to assign. Here is a sample code that has been provided for your perusal.

Script (env_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The value of the USER environment variable, which represents the current username, is assigned to the Bash variable username. Then the output is displayed using the echo command.

Assign Value from Environmental Bash Variable

Case 05: Default Value Assignment

In Bash , you can assign default values to variables using the ${variable:-default} syntax . Note that this default value assignment does not change the original value of the variable; it only assigns a default value if the variable is empty or unset . Here’s a script to learn how it works.

Script (default_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The next line stores a null string to the variable . The ${ variable:-Softeko } expression checks if the variable is unset or empty. As the variable is empty, it assigns the default value ( Softeko in this case) to the variable . In the second portion of the code, the LinuxSimply string is stored as a variable. Then the assigned variable is printed using the echo command .

Default Value Assignment

Case 06: Assigning Value by Taking Input From the User

In Bash , you can assign a value from the user by using the read command. Remember we have used this command in Case 2 . Apart from assigning value in a single line, the read command allows you to prompt the user for input and assign it to a variable. Here’s an example given below.

Script (user_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The read command is used to read the input from the user and assign it to the name variable . The user is prompted with the message “ Enter your name: “, and the value they enter is stored in the name variable. Finally, the script displays a message using the entered value.

Assigning Value by Taking Input from the User

Case 07: Using the “let” Command for Variable Assignment

In Bash , the let command can be used for arithmetic operations and variable assignment. When using let for variable assignment, it allows you to perform arithmetic operations and assign the result to a variable .

Script (let_var_assign.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. then the let command performs arithmetic operations and assigns the results to variables num. Later, the echo command has been used to display the value stored in the num variable.

Using the let Command for Variable Assignment

Case 08: Assigning Shell Command Output to a Variable

Lastly, you can assign the output of a shell command to a variable using command substitution . There are two common ways to achieve this: using backticks ( “) or using the $()   syntax. Note that $() syntax is generally preferable over backticks as it provides better readability and nesting capability, and it avoids some issues with quoting. Here’s an example that I have provided using both cases.

Script (shell_command_var.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The output of the ls -l command (which lists the contents of the current directory in long format) allocates to the variable output1 using backticks . Similarly, the output of the date command (which displays the current date and time) is assigned to the variable output2 using the $() syntax . The echo command displays both output1 and output2 .

Assigning Shell Command Output to a Variable

Assignment on Assigning Variables in Bash Scripts

Finally, I have provided two assignments based on today’s discussion. Don’t forget to check this out.

  • Difference: ?
  • Quotient: ?
  • Remainder: ?
  • Write a Bash script to find and display the name of the largest file using variables in a specified directory.

In conclusion, assigning variable Bash is a crucial aspect of scripting, allowing developers to store and manipulate data efficiently. This article explored several cases to assign variables in Bash, including single-variable assignments , multi-variable assignments in a single line , assigning values from environmental variables, and so on. Each case has its advantages and limitations, and the choice depends on the specific needs of the script or program. However, if you have any questions regarding this article, feel free to comment below. I will get back to you soon. Thank You!

People Also Ask

Related Articles

  • How to Declare Variable in Bash Scripts? [5 Practical Cases]
  • Bash Variable Naming Conventions in Shell Script [6 Rules]
  • How to Check Variable Value Using Bash Scripts? [5 Cases]
  • How to Use Default Value in Bash Scripts? [2 Methods]
  • How to Use Set – $Variable in Bash Scripts? [2 Examples]
  • How to Read Environment Variables in Bash Script? [2 Methods]
  • How to Export Environment Variables with Bash? [4 Examples]

<< Go Back to Variable Declaration and Assignment  | Bash Variables | Bash Scripting Tutorial

Mohammad Shah Miran

Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

linuxsimply white logo

Get In Touch!

card

Legal Corner

dmca

Copyright © 2024 LinuxSimply | All Rights Reserved.

Get the Reddit app

Wake me up when September ends.

While loop is broken [beginner]

The purpose of this program is to set the variable "num" to 0 and have it increment by 1 every time the while loop cycles until the number is greater than 9. Whenever I run the program, though, the shell infinitely prints "0 is less than ten; bash: let: 0=1: attempted assignment to non-variable (error token is "=1")". What can I do to fix the program?

edit: I just changed = to == in the loop and now it's infinitely printing "0 is less than ten"

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Bash: "command not found" on simple variable assignment

Here's a simple version of my script which displays the failure:

When I echo the variables, I get the values I put in, but it also emits an error. What am I doing wrong?

The first two lines are being emitted to stderr, while the next three are being output to stdout.

My platform is fedora 15, bash version 4.2.10.

codeforester's user avatar

3 Answers 3

You can add colon:

The trick with a ":" (no-operation command) is that, nothing gets executated, but parameters gets expanded. Personally I don't like this syntax, because for people not knowing this trick the code is difficult to understand.

You can use this as an alternative:

or longer, more portable (but IMHO more readable):

Michał Šrajer's user avatar

  • Huh, I did a quick man : and I think the : will do what I like. I'll make sure to comment this thoroughly though. Are there any better alternatives? –  beatgammit Commented Aug 6, 2011 at 21:54
  • the ":" is a builtin. You need to "help :" or "man bash". See "SHELL BUILTIN COMMANDS" section. –  Michał Šrajer Commented Aug 6, 2011 at 22:29

Putting a variable on a line by itself will execute the command stored in the variable. That an assignment is being performed at the same time is incidental.

In short, don't do that.

Ignacio Vazquez-Abrams's user avatar

  • Hmph, I don't know why I didn't realize that... I guess that solves my problem. Thanks! –  beatgammit Commented Aug 6, 2011 at 21:44

It's simply

If you use $(variable_name:=value} bash substitutes the variable_name if it is set otherwise it uses the default you specified.

Karoly Horvath's user avatar

  • That was the point. Sorry about not specifying that in the question. –  beatgammit Commented Aug 6, 2011 at 21:48

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged bash or ask your own question .

  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Announcing a change to the data-dump process

Hot Network Questions

  • On how to produce videos like this one
  • tikz & amsmath: how can I align math formulas within a tikz matrix?
  • is responding with "Entschuldigung?" to something I could not understand considered impolite?
  • In what way are we one in Christ Jesus?
  • Two-form that evaluates to zero when input nonzero vectors are not linearly dependent
  • Why do doctors seem to overcharge for services?
  • Adjust size of symbol after rotation
  • Is ksh-syntax (Korn shell) compatible to bash?
  • Which programming language first used negative indexing to mean counting from the end?
  • Can I replace the Sun with a non-nuclear equivalent?
  • How to finish off a sudoku with lots of options?
  • Newtonian vs General Relativistic light deflection angle
  • Why is transfer of heat very slow as compared to transfer of sound in solids?
  • Are there official, standard, or conventional names for the screen RAM addresses on the ZX Spectrum?
  • "Highly skilled" or "high-skilled"?
  • Why is the ntptrace peers list inconsistent with the ntpq peers list?
  • Boundedness of sum of sin(sin(n))
  • Lexicographically earliest permutation of the initial segment of nonnegative integers subject to divisibility constraints
  • Motor replacement
  • Why do C++ sequence containers have an "assign" method but associative containers do not?
  • Relocate Windows Users directory to another hard disk
  • What does it mean to write to the Register of an IC?
  • Are dice pools public knowledge in Dogs in the Vineyard/DOGS?
  • How to calculate an integral over the complex unit sphere

bash attempted assignment to non variable

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Bash: Variable assignment doesn't seem to 'stick' [duplicate]

I am having a hard time tracking down the reason my 'boolean' flag variable won't stay false when a test fails inside a while loop.

The script involves a few loops but essentially it is intended to play two random albums every morning when it is triggered by cron. I used to have a simple one-liner script that selected two albums but I wanted to blacklist any albums that I didn't want playing (i.e. christmas music albums).

To do this, I had it read a wakeUp_blacklist.txt file with the names of albums I didn't want to hear so it can reject any matches. This compares the blacklisted albums line-by-line with one randomly selected album and tests for a match. If a match is found, it flags the match as a failure ( pass = false ) and SHOULD loop back and select a different album. For some reason, as soon as the execution exits the read | while loop, the flag switches back to true and so another album is never selected!

Here is my code and an example output:

So, if I run this a few times, it will eventually chose one of the blacklisted albums and give output that looks like:

You can see that towards the end, when the blacklist entry is a match for the selected album (German_Christmas) the test fails, the pass variable is false but the first output that checks pass value outside the read | while loop shows it being true again!

I understand that my script may not be as efficient as possible yet but I want to understand what is happening here before I move on. Any suggestions?

  • shell-script

Volker Siegel's user avatar

Each command in a pipeline is executed in its own subshell

A subshell is another instance of bash , with its own state. That means that any variable changes you make on the right-hand side of a | conceptually "belong" to a different bash instance — the existing values and declarations at the start are copied in, but the variables have different storage locations and modifications to them are visible only inside that subshell (you can think of this as working like fork , if you like).

When the subshell completes, that copy of the variable ceases to exist. The "outer" shell only ever sees its own, unmodified, copy of the variable, which is why it appears that you're losing your modifications outside the loop.

In this case, you can avoid using a subshell with simple redirection :

Now, the while loop runs in your main shell, and no subshell is created. The contents of the blacklist file are still given as standard input to the loop using < file redirection . All variables exist inside the same environment. This approach also avoids a useless use of cat .

Some other shells (notably zsh ), don't have this behaviour to start with, and you can modify variables on the right-hand side of pipelines freely.

Michael Homer's user avatar

  • 1 Ah... I thought it must be some sort of scope-like issue... I hadn't occurred to me that the pipe would make the whole loop execute in a subshell. Thank you! –  Justin Frahm Commented Sep 15, 2014 at 0:08
  • Bash (and possibly other shells) pitfall's number 8 ( mywiki.wooledge.org/BashPitfalls ) –  Olivier Dulac Commented Sep 15, 2014 at 7:40
  • Also relevant: I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read? –  Anthony Geoghegan Commented Sep 15, 2014 at 9:11
  • @Michael Homer: Maybe you should search the site before answering question. See: unix.stackexchange.com/questions/9954/… –  cuonglm Commented Sep 15, 2014 at 11:48
  • I came here to investigate why my shell skript does not assign a value to a variable. I do the skript, it does not work properly. Then I check the variable in terminal and it is empty. Am I correctly assuming that the skript also uses another instance of bash? I use Debian on a Raspberry and the skript starts with #!/bin/bash. –  bomben Commented May 2, 2019 at 11:14

Not the answer you're looking for? Browse other questions tagged bash shell-script variable .

  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Announcing a change to the data-dump process

Hot Network Questions

  • Determine the area of region satisfying the given condition
  • Extract part of an Excel formula in another cell
  • What does it mean to write to the Register of an IC?
  • Are There Any Recomendation of Aircraft Design Books Written By Russian Author?
  • Is ksh-syntax (Korn shell) compatible to bash?
  • Count number display: "99+" vs full number
  • What's wrong with constructions like "Dragons are big, green, and eat people."?
  • What are the specific terms for breaking up English words into roots/components
  • Is leveling this ground and removing plastic by the side of my house a bad idea?
  • Ampleness verifiable over faithfully flat cover
  • Does Voltage of solar cell depends on Intensity of light?
  • Does space dust fall on the roof of my house and if so can I detect it with a cheap home microscope?
  • Is it possible for a flying superhuman to avoid detection in todays society?
  • A complex eight pieces endgame
  • Round robin tournament: Who won the game between the Reds and the Blues?
  • Is expired sushi rice still good
  • Two-form that evaluates to zero when input nonzero vectors are not linearly dependent
  • Political Relations on an Interstellar Scale
  • Is "Non-Trivial amount of work" a correct phrase?
  • Cannot get clear photos with 48 megapixel camera
  • Are there official, standard, or conventional names for the screen RAM addresses on the ZX Spectrum?
  • How many of the 16 cells of the grid could contain the black dot?
  • Is it bad to have similar themes in my novels?
  • Boundedness of sum of sin(sin(n))

bash attempted assignment to non variable

IMAGES

  1. Unix & Linux: Attempted assignment to non-variable? (3 Solutions

    bash attempted assignment to non variable

  2. bash variable assignment special characters

    bash attempted assignment to non variable

  3. What Are Bash Variables and How Can You Use Them?

    bash attempted assignment to non variable

  4. What Are Bash Variables and How Can You Use Them?

    bash attempted assignment to non variable

  5. Learn Difference Between $$ and $BASHPID in Bash

    bash attempted assignment to non variable

  6. W08 Assignment

    bash attempted assignment to non variable

VIDEO

  1. Working with BASH shell

  2. Digital Story Assignment: A Leo Birthday Bash

  3. Bash Script lesson 4: How to use Constant variable in Bash

  4. learn bash data structure variable , array , list with vagrant and virtualbox

  5. Functions In Bash

  6. Bash Scripting

COMMENTS

  1. "Attempted assignment to a non-variable" in bash

    1 I'm new to Bash and I've been having issues with creating a script. What this script does is take numbers and add them to a total. However, I can't get total to work.It constantly claims that total is a non-variable despite it being assigned earlier in the program.

  2. Attempted assignment to non-variable?

    The only way to assign values to positional parameters in bash is via the set builtin: set a b. assigns a to $1 and b to $2 (note that it resets the whole positional parameter list, so $3, $4 ... are lost). So here, you could do: set -- "$(($1 / 1000))" To assign the value of $1 divided by 1000 to $1. By contrast, with zsh (a more advanced ...

  3. bash

    Inside (( ... )) arithmetic evaluation, = is an assignment operator not a logical comparison operator. So $(($w = 0)) is dereferencing variable w, and then attempting to assign the value 0 to its value.

  4. Bash's conditional operator and assignment

    But when I use assignment operators after :, I got 'attempted assignment to non-variable' error:

  5. Bash

    2. The reason this occurs is that the while loop is part of a pipeline, and (at least in bash) any shell commands in a pipeline always get executed in a subshell. When you set mysvn inside the loop, it gets set in the subshell; when the loop ends, the subshell exits and this value is lost.

  6. bash

    This technique allows for a variable to be assigned a value if another variable is either empty or is undefined. NOTE: This "other variable" can be the same or another variable. excerpt. ${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

  7. Unix & Linux: Attempted assignment to non-variable? (3 Solutions

    Unix & Linux: Attempted assignment to non-variable? (3 Solutions!!) Roel Van de Paar 122K subscribers 0 1 view 2 years ago Unix and Linux-23

  8. How to Work with Variables in Bash

    Want to take your Linux command-line skills to the next level? Here's everything you need to know to start working with variables.

  9. How to Assign Variable in Bash Script? [8 Practical Cases]

    To assign a value to a single variable in Bash script, you can use the following syntax: variable=value. However, replace the variable with the name of the variable you want to assign, and the value with the desired value you want to assign to that variable.

  10. bash

    1. '|' is used to redirect the output of one command to the next command .In your case NO output is produced in the first command bcz its just assigning value to a variable . What you have to use is : ( try this ) && -> executes the trailing command if the first command succeeded only.AND Operator.

  11. Ubuntu: Attempted assignment to non-variable (error token is "= 0

    Ubuntu: Attempted assignment to non-variable (error token is "= 0 ") Roel Van de Paar 161K subscribers 29 views 4 years ago ...more

  12. While loop is broken [beginner] : r/bash

    The purpose of this program is to set the variable "num" to 0 and have it increment by 1 every time the while loop cycles until the number is greater than 9. Whenever I run the program, though, the shell infinitely prints "0 is less than ten; bash: let: 0=1: attempted assignment to non-variable (error token is "=1")".

  13. Bash assign output/error to variable

    IIRC the double quotes around process substitution aren't necessary when assigning to a variable. They're only necessary to avoid word splitting when process substitution is passed as argument to another command.

  14. bash Arithmetic Syntax Errors

    bash Arithmetic Syntax Errors Programming This forum is for all programming questions. The question does not have to be directly related to Linux and any language is fair game.

  15. In bash script variable assignment does not work

    That declares the variable nextcount with the integer attribute, which causes arithmetic evaluation to be performed on it automatically whenever it is assigned. (Run help declare in bash or look here for details.) This is not a standard POSIX shell feature, but bash supports it. The assignment does not need to immediately follow the declare ...

  16. Bash: "command not found" on simple variable assignment

    3 Putting a variable on a line by itself will execute the command stored in the variable. That an assignment is being performed at the same time is incidental. In short, don't do that.

  17. Bash: Variable assignment doesn't seem to 'stick' [duplicate]

    That means that any variable changes you make on the right-hand side of a | conceptually "belong" to a different bash instance — the existing values and declarations at the start are copied in, but the variables have different storage locations and modifications to them are visible only inside that subshell (you can think of this as working ...