Initializing Bash variables - Is it required, recommended or define as you go

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
10
down vote

favorite
2












Is there any advantage/disadvantage of initializing the value of a bash variable in the script, either before the main code, or local variables in a function before assigning the actual value to it?



Do I need to do something like this:



init()

name=""
name=$1


init "Mark"


Is there any risk of variables being initialized with garbage values (if not initialized) and that having a negative effect of the values of the variables?







share|improve this question


















  • 1




    Where did you get this idea?
    – DoritoStyle
    Aug 22 at 8:23






  • 5




    @DoritoStyle Well, if one is used to lower level languages, such as C, then this is a perfectly valid thing to be concerned about.
    – Kusalananda
    Aug 22 at 8:26














up vote
10
down vote

favorite
2












Is there any advantage/disadvantage of initializing the value of a bash variable in the script, either before the main code, or local variables in a function before assigning the actual value to it?



Do I need to do something like this:



init()

name=""
name=$1


init "Mark"


Is there any risk of variables being initialized with garbage values (if not initialized) and that having a negative effect of the values of the variables?







share|improve this question


















  • 1




    Where did you get this idea?
    – DoritoStyle
    Aug 22 at 8:23






  • 5




    @DoritoStyle Well, if one is used to lower level languages, such as C, then this is a perfectly valid thing to be concerned about.
    – Kusalananda
    Aug 22 at 8:26












up vote
10
down vote

favorite
2









up vote
10
down vote

favorite
2






2





Is there any advantage/disadvantage of initializing the value of a bash variable in the script, either before the main code, or local variables in a function before assigning the actual value to it?



Do I need to do something like this:



init()

name=""
name=$1


init "Mark"


Is there any risk of variables being initialized with garbage values (if not initialized) and that having a negative effect of the values of the variables?







share|improve this question














Is there any advantage/disadvantage of initializing the value of a bash variable in the script, either before the main code, or local variables in a function before assigning the actual value to it?



Do I need to do something like this:



init()

name=""
name=$1


init "Mark"


Is there any risk of variables being initialized with garbage values (if not initialized) and that having a negative effect of the values of the variables?









share|improve this question













share|improve this question




share|improve this question








edited Aug 21 at 15:59









ilkkachu

50.4k677138




50.4k677138










asked Aug 21 at 15:48









Cyrus

536




536







  • 1




    Where did you get this idea?
    – DoritoStyle
    Aug 22 at 8:23






  • 5




    @DoritoStyle Well, if one is used to lower level languages, such as C, then this is a perfectly valid thing to be concerned about.
    – Kusalananda
    Aug 22 at 8:26












  • 1




    Where did you get this idea?
    – DoritoStyle
    Aug 22 at 8:23






  • 5




    @DoritoStyle Well, if one is used to lower level languages, such as C, then this is a perfectly valid thing to be concerned about.
    – Kusalananda
    Aug 22 at 8:26







1




1




Where did you get this idea?
– DoritoStyle
Aug 22 at 8:23




Where did you get this idea?
– DoritoStyle
Aug 22 at 8:23




5




5




@DoritoStyle Well, if one is used to lower level languages, such as C, then this is a perfectly valid thing to be concerned about.
– Kusalananda
Aug 22 at 8:26




@DoritoStyle Well, if one is used to lower level languages, such as C, then this is a perfectly valid thing to be concerned about.
– Kusalananda
Aug 22 at 8:26










2 Answers
2






active

oldest

votes

















up vote
20
down vote



accepted










There is no benefit to assigning an empty string to a variable and then immediately assigning another variable string to it. An assignment of a value to a shell variable will completely overwrite its previous value.



There is to my knowledge no recommendation that says that you should explicitly initialize variables to empty strings. In fact, doing so may mask errors under some circumstances (errors that would otherwise be apparent if running under set -u, see below).



An unset variable, being unused since the start of a script or explicitly unset by running the unset command on it, will have no value. The value of such a variable will be nothing. If used as "$myvariable", you will get the equivalent of "".



If the shell option nounset is set with either set -o nounset or set -u, then referencing an unset variable will cause the shell to produce an error (and a non-interactive shell would terminate):



$ set -u
$ echo "$myvariable"
/bin/sh: myvariable: parameter not set


or, in bash:



$ set -u
$ echo "$myvariable"
bash: myvariable: unbound variable


Shell variables will be initialized by the environment if the name of the variable corresponds to an existing environment variable.



If you expect that you are using a variable that may be initialized by the environment in this way (and if it's unwanted), then you may explicitly unset it before the main part of your script:



unset myvariable # unset so that it doesn't inherit a value from the environment


which would also remove it as an environment variable, or, you may simply ignore its initial value and just overwrite it with an assignment (which would make the environment variable change value too).



You would never encounter uninitialized garbage in a shell variable (unless, as stated, that garbage already existed in an environment variable by the same name).






share|improve this answer


















  • 2




    While there is no value to setting a variable to an empty value and then immediately setting it as the OP literally does, there is value in setting an empty value (or unsetting) prior to running some kind of for or while loop to set it to a calculated value if there is any chance that loop will not actually run due to the condition(s) not being met; and the variable might have been set to some other value in the environment the script inherited. But it's arguably better to put everything in a main() and define the variables as local.
    – Monty Harder
    Aug 21 at 17:52











  • You can also detect unset variables using the parameter expansion operators, by omitting the :, e.g. $myvariable-defaultvalue
    – Barmar
    Aug 22 at 19:29

















up vote
2
down vote













The advantage of declaring local variables in a function is that you can easily copy the code.



For example, say I have a function in my .bashrc:



foo()
local name
name="$1"
echo "$name"



If I want to make it into a script, I just ignore the local statement and copy everything else:



#!/bin/bash
name="$1"
echo "$name"


If the declaration and assignment were in the same line, I'd have to manually edit out the local part before I could turn it into a script:



foo()
local name="$1"
echo "$name"



In this example it's not a big deal, but if you're dealing with bigger, more complex functions, it can get more painful.






share|improve this answer






















  • The question wasn't about combining the declaration and initialization. It was about whether to initialize with an empty value before assigning a real value.
    – Barmar
    Aug 22 at 19:26










  • @Barmar Oh, I just looked up "initialization". I thought it was synonymous with "declaration"...
    – wjandrea
    Aug 22 at 20:02










Your Answer







StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "106"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: false,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













 

draft saved


draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f463904%2finitializing-bash-variables-is-it-required-recommended-or-define-as-you-go%23new-answer', 'question_page');

);

Post as a guest






























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
20
down vote



accepted










There is no benefit to assigning an empty string to a variable and then immediately assigning another variable string to it. An assignment of a value to a shell variable will completely overwrite its previous value.



There is to my knowledge no recommendation that says that you should explicitly initialize variables to empty strings. In fact, doing so may mask errors under some circumstances (errors that would otherwise be apparent if running under set -u, see below).



An unset variable, being unused since the start of a script or explicitly unset by running the unset command on it, will have no value. The value of such a variable will be nothing. If used as "$myvariable", you will get the equivalent of "".



If the shell option nounset is set with either set -o nounset or set -u, then referencing an unset variable will cause the shell to produce an error (and a non-interactive shell would terminate):



$ set -u
$ echo "$myvariable"
/bin/sh: myvariable: parameter not set


or, in bash:



$ set -u
$ echo "$myvariable"
bash: myvariable: unbound variable


Shell variables will be initialized by the environment if the name of the variable corresponds to an existing environment variable.



If you expect that you are using a variable that may be initialized by the environment in this way (and if it's unwanted), then you may explicitly unset it before the main part of your script:



unset myvariable # unset so that it doesn't inherit a value from the environment


which would also remove it as an environment variable, or, you may simply ignore its initial value and just overwrite it with an assignment (which would make the environment variable change value too).



You would never encounter uninitialized garbage in a shell variable (unless, as stated, that garbage already existed in an environment variable by the same name).






share|improve this answer


















  • 2




    While there is no value to setting a variable to an empty value and then immediately setting it as the OP literally does, there is value in setting an empty value (or unsetting) prior to running some kind of for or while loop to set it to a calculated value if there is any chance that loop will not actually run due to the condition(s) not being met; and the variable might have been set to some other value in the environment the script inherited. But it's arguably better to put everything in a main() and define the variables as local.
    – Monty Harder
    Aug 21 at 17:52











  • You can also detect unset variables using the parameter expansion operators, by omitting the :, e.g. $myvariable-defaultvalue
    – Barmar
    Aug 22 at 19:29














up vote
20
down vote



accepted










There is no benefit to assigning an empty string to a variable and then immediately assigning another variable string to it. An assignment of a value to a shell variable will completely overwrite its previous value.



There is to my knowledge no recommendation that says that you should explicitly initialize variables to empty strings. In fact, doing so may mask errors under some circumstances (errors that would otherwise be apparent if running under set -u, see below).



An unset variable, being unused since the start of a script or explicitly unset by running the unset command on it, will have no value. The value of such a variable will be nothing. If used as "$myvariable", you will get the equivalent of "".



If the shell option nounset is set with either set -o nounset or set -u, then referencing an unset variable will cause the shell to produce an error (and a non-interactive shell would terminate):



$ set -u
$ echo "$myvariable"
/bin/sh: myvariable: parameter not set


or, in bash:



$ set -u
$ echo "$myvariable"
bash: myvariable: unbound variable


Shell variables will be initialized by the environment if the name of the variable corresponds to an existing environment variable.



If you expect that you are using a variable that may be initialized by the environment in this way (and if it's unwanted), then you may explicitly unset it before the main part of your script:



unset myvariable # unset so that it doesn't inherit a value from the environment


which would also remove it as an environment variable, or, you may simply ignore its initial value and just overwrite it with an assignment (which would make the environment variable change value too).



You would never encounter uninitialized garbage in a shell variable (unless, as stated, that garbage already existed in an environment variable by the same name).






share|improve this answer


















  • 2




    While there is no value to setting a variable to an empty value and then immediately setting it as the OP literally does, there is value in setting an empty value (or unsetting) prior to running some kind of for or while loop to set it to a calculated value if there is any chance that loop will not actually run due to the condition(s) not being met; and the variable might have been set to some other value in the environment the script inherited. But it's arguably better to put everything in a main() and define the variables as local.
    – Monty Harder
    Aug 21 at 17:52











  • You can also detect unset variables using the parameter expansion operators, by omitting the :, e.g. $myvariable-defaultvalue
    – Barmar
    Aug 22 at 19:29












up vote
20
down vote



accepted







up vote
20
down vote



accepted






There is no benefit to assigning an empty string to a variable and then immediately assigning another variable string to it. An assignment of a value to a shell variable will completely overwrite its previous value.



There is to my knowledge no recommendation that says that you should explicitly initialize variables to empty strings. In fact, doing so may mask errors under some circumstances (errors that would otherwise be apparent if running under set -u, see below).



An unset variable, being unused since the start of a script or explicitly unset by running the unset command on it, will have no value. The value of such a variable will be nothing. If used as "$myvariable", you will get the equivalent of "".



If the shell option nounset is set with either set -o nounset or set -u, then referencing an unset variable will cause the shell to produce an error (and a non-interactive shell would terminate):



$ set -u
$ echo "$myvariable"
/bin/sh: myvariable: parameter not set


or, in bash:



$ set -u
$ echo "$myvariable"
bash: myvariable: unbound variable


Shell variables will be initialized by the environment if the name of the variable corresponds to an existing environment variable.



If you expect that you are using a variable that may be initialized by the environment in this way (and if it's unwanted), then you may explicitly unset it before the main part of your script:



unset myvariable # unset so that it doesn't inherit a value from the environment


which would also remove it as an environment variable, or, you may simply ignore its initial value and just overwrite it with an assignment (which would make the environment variable change value too).



You would never encounter uninitialized garbage in a shell variable (unless, as stated, that garbage already existed in an environment variable by the same name).






share|improve this answer














There is no benefit to assigning an empty string to a variable and then immediately assigning another variable string to it. An assignment of a value to a shell variable will completely overwrite its previous value.



There is to my knowledge no recommendation that says that you should explicitly initialize variables to empty strings. In fact, doing so may mask errors under some circumstances (errors that would otherwise be apparent if running under set -u, see below).



An unset variable, being unused since the start of a script or explicitly unset by running the unset command on it, will have no value. The value of such a variable will be nothing. If used as "$myvariable", you will get the equivalent of "".



If the shell option nounset is set with either set -o nounset or set -u, then referencing an unset variable will cause the shell to produce an error (and a non-interactive shell would terminate):



$ set -u
$ echo "$myvariable"
/bin/sh: myvariable: parameter not set


or, in bash:



$ set -u
$ echo "$myvariable"
bash: myvariable: unbound variable


Shell variables will be initialized by the environment if the name of the variable corresponds to an existing environment variable.



If you expect that you are using a variable that may be initialized by the environment in this way (and if it's unwanted), then you may explicitly unset it before the main part of your script:



unset myvariable # unset so that it doesn't inherit a value from the environment


which would also remove it as an environment variable, or, you may simply ignore its initial value and just overwrite it with an assignment (which would make the environment variable change value too).



You would never encounter uninitialized garbage in a shell variable (unless, as stated, that garbage already existed in an environment variable by the same name).







share|improve this answer














share|improve this answer



share|improve this answer








edited Aug 21 at 17:19

























answered Aug 21 at 15:58









Kusalananda

105k14207325




105k14207325







  • 2




    While there is no value to setting a variable to an empty value and then immediately setting it as the OP literally does, there is value in setting an empty value (or unsetting) prior to running some kind of for or while loop to set it to a calculated value if there is any chance that loop will not actually run due to the condition(s) not being met; and the variable might have been set to some other value in the environment the script inherited. But it's arguably better to put everything in a main() and define the variables as local.
    – Monty Harder
    Aug 21 at 17:52











  • You can also detect unset variables using the parameter expansion operators, by omitting the :, e.g. $myvariable-defaultvalue
    – Barmar
    Aug 22 at 19:29












  • 2




    While there is no value to setting a variable to an empty value and then immediately setting it as the OP literally does, there is value in setting an empty value (or unsetting) prior to running some kind of for or while loop to set it to a calculated value if there is any chance that loop will not actually run due to the condition(s) not being met; and the variable might have been set to some other value in the environment the script inherited. But it's arguably better to put everything in a main() and define the variables as local.
    – Monty Harder
    Aug 21 at 17:52











  • You can also detect unset variables using the parameter expansion operators, by omitting the :, e.g. $myvariable-defaultvalue
    – Barmar
    Aug 22 at 19:29







2




2




While there is no value to setting a variable to an empty value and then immediately setting it as the OP literally does, there is value in setting an empty value (or unsetting) prior to running some kind of for or while loop to set it to a calculated value if there is any chance that loop will not actually run due to the condition(s) not being met; and the variable might have been set to some other value in the environment the script inherited. But it's arguably better to put everything in a main() and define the variables as local.
– Monty Harder
Aug 21 at 17:52





While there is no value to setting a variable to an empty value and then immediately setting it as the OP literally does, there is value in setting an empty value (or unsetting) prior to running some kind of for or while loop to set it to a calculated value if there is any chance that loop will not actually run due to the condition(s) not being met; and the variable might have been set to some other value in the environment the script inherited. But it's arguably better to put everything in a main() and define the variables as local.
– Monty Harder
Aug 21 at 17:52













You can also detect unset variables using the parameter expansion operators, by omitting the :, e.g. $myvariable-defaultvalue
– Barmar
Aug 22 at 19:29




You can also detect unset variables using the parameter expansion operators, by omitting the :, e.g. $myvariable-defaultvalue
– Barmar
Aug 22 at 19:29












up vote
2
down vote













The advantage of declaring local variables in a function is that you can easily copy the code.



For example, say I have a function in my .bashrc:



foo()
local name
name="$1"
echo "$name"



If I want to make it into a script, I just ignore the local statement and copy everything else:



#!/bin/bash
name="$1"
echo "$name"


If the declaration and assignment were in the same line, I'd have to manually edit out the local part before I could turn it into a script:



foo()
local name="$1"
echo "$name"



In this example it's not a big deal, but if you're dealing with bigger, more complex functions, it can get more painful.






share|improve this answer






















  • The question wasn't about combining the declaration and initialization. It was about whether to initialize with an empty value before assigning a real value.
    – Barmar
    Aug 22 at 19:26










  • @Barmar Oh, I just looked up "initialization". I thought it was synonymous with "declaration"...
    – wjandrea
    Aug 22 at 20:02














up vote
2
down vote













The advantage of declaring local variables in a function is that you can easily copy the code.



For example, say I have a function in my .bashrc:



foo()
local name
name="$1"
echo "$name"



If I want to make it into a script, I just ignore the local statement and copy everything else:



#!/bin/bash
name="$1"
echo "$name"


If the declaration and assignment were in the same line, I'd have to manually edit out the local part before I could turn it into a script:



foo()
local name="$1"
echo "$name"



In this example it's not a big deal, but if you're dealing with bigger, more complex functions, it can get more painful.






share|improve this answer






















  • The question wasn't about combining the declaration and initialization. It was about whether to initialize with an empty value before assigning a real value.
    – Barmar
    Aug 22 at 19:26










  • @Barmar Oh, I just looked up "initialization". I thought it was synonymous with "declaration"...
    – wjandrea
    Aug 22 at 20:02












up vote
2
down vote










up vote
2
down vote









The advantage of declaring local variables in a function is that you can easily copy the code.



For example, say I have a function in my .bashrc:



foo()
local name
name="$1"
echo "$name"



If I want to make it into a script, I just ignore the local statement and copy everything else:



#!/bin/bash
name="$1"
echo "$name"


If the declaration and assignment were in the same line, I'd have to manually edit out the local part before I could turn it into a script:



foo()
local name="$1"
echo "$name"



In this example it's not a big deal, but if you're dealing with bigger, more complex functions, it can get more painful.






share|improve this answer














The advantage of declaring local variables in a function is that you can easily copy the code.



For example, say I have a function in my .bashrc:



foo()
local name
name="$1"
echo "$name"



If I want to make it into a script, I just ignore the local statement and copy everything else:



#!/bin/bash
name="$1"
echo "$name"


If the declaration and assignment were in the same line, I'd have to manually edit out the local part before I could turn it into a script:



foo()
local name="$1"
echo "$name"



In this example it's not a big deal, but if you're dealing with bigger, more complex functions, it can get more painful.







share|improve this answer














share|improve this answer



share|improve this answer








edited Aug 22 at 20:03

























answered Aug 21 at 19:38









wjandrea

462312




462312











  • The question wasn't about combining the declaration and initialization. It was about whether to initialize with an empty value before assigning a real value.
    – Barmar
    Aug 22 at 19:26










  • @Barmar Oh, I just looked up "initialization". I thought it was synonymous with "declaration"...
    – wjandrea
    Aug 22 at 20:02
















  • The question wasn't about combining the declaration and initialization. It was about whether to initialize with an empty value before assigning a real value.
    – Barmar
    Aug 22 at 19:26










  • @Barmar Oh, I just looked up "initialization". I thought it was synonymous with "declaration"...
    – wjandrea
    Aug 22 at 20:02















The question wasn't about combining the declaration and initialization. It was about whether to initialize with an empty value before assigning a real value.
– Barmar
Aug 22 at 19:26




The question wasn't about combining the declaration and initialization. It was about whether to initialize with an empty value before assigning a real value.
– Barmar
Aug 22 at 19:26












@Barmar Oh, I just looked up "initialization". I thought it was synonymous with "declaration"...
– wjandrea
Aug 22 at 20:02




@Barmar Oh, I just looked up "initialization". I thought it was synonymous with "declaration"...
– wjandrea
Aug 22 at 20:02

















 

draft saved


draft discarded















































 


draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f463904%2finitializing-bash-variables-is-it-required-recommended-or-define-as-you-go%23new-answer', 'question_page');

);

Post as a guest













































































Comments

Popular posts from this blog

White Anglo-Saxon Protestant

Is the Concept of Multiple Fantasy Races Scientifically Flawed? [closed]

One-line joke