In Terminal, how can I set a new variable and assign a value to it? Let's say I want to compare two files with long file names and then also perform some other operations. Because of the long file names I'd like to create two variables, assign value to each variable and use it as place-holder. I need something like the following:
set var1 = 'long-file-name1'
set var2 = 'long-file-name2'
diff var1 var2
The pseudocode (or code for some other shell or programming language) in your question translates to the following Bash commands:
The syntax
$var1
is parameter expansion. This replaces the variablevar1
with its value--in this case, with the filename stored in it. Unquoted parameter expansion triggers word splitting (also called "field splitting") and globbing (also called "filename expansion" and "pathname expansion"). Usually you don't want those further expansions to occur. Except when you specifically know you want them, you should make sure to enclose all occurrences of parameter expansion in double quotes. (Single quotes are even more powerful--they would prevent parameter expansion from happening, too.)That runs the
diff
command with the filename stored invar1
passed as its first command-line argument and the filename stored invar2
passed as its second command-line argument. This causesdiff
to compare the contents of the files, as you intend, just as it would if you had run:You will notice that I have not used the
export
command. That's because, in this case, theexport
command is neither necessary nor appropriate for what you are doing. When the value of a variable only needs to be expanded in your shell--and not accessed by programs started from your shell--then you do not need to (and should not) useexport
.If your system had a strange
diff
command that read filenames from environment variables calledvar1
andvar2
rather than taking filenames as command-line arguments, then you would need to export your variables. But that's not howdiff
works. Thediff
command is not accessing--and does not know anything about--your variables. The shell is expanding them to produce the arguments it then passes todiff
.You can store the file name in a variable in bash simply by assigning it
For example:
variable=filename && variable2=filename2
you can then
diff
the two files using those variables like thisdiff $variable $variable2
NB:if your filenames have spaces it is best to double quote both the filenames and the variables especially when performing operations with them