0

Supposing some strings (like 123 or abc or test123) would automatically appear on the screen after last command and I cannot know the exact value of the string in advance.

Next I want to make a new directory named after that string (like ./123/ or ./abc/ or ./test123/), which means the string should be given to a variable var so that the new directory could be created by mkdir $var.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Bo-Yuan
  • 61

1 Answers1

1

You can use backticks to store the result of a command (in my example, it's uname) on a variable, then echo it onscreen, and eventually use it as argument to mkdir:

FOO=`uname -n`
echo "$FOO"
mkdir "$FOO" 

The excellent Advanced Bash-Scripting Guide has a whole chapter about Command Substitution.

As @KalvinLee commented, the preferred format is now $(...):

FOO=$(uname -n)
dr_
  • 29,602
  • 4
    If one needs extra fanciness, the $(...) syntax is worth considering. There's an explanation somewhere else on ULSE that I can't find now. – Kalvin Lee Oct 24 '16 at 13:50
  • 2
    I've modified your post to include quotes. If the OP wants to create paths or files and doesn't use quotes, he will get wrong results if there are spaces in the variable. – MatthewRock Oct 24 '16 at 13:52
  • Thanks for the help. But according to your method, it seems that the result of last command is already known. What if the last command generates random strings on the screen and there is no way to know the strings in advance? Anyway, thanks for the reply. – Bo-Yuan Oct 24 '16 at 13:55
  • @Bo-YuanNing Replace uname -n with the name of your random-string-generator command and you'll have what you want. – dr_ Oct 24 '16 at 13:57
  • @dr01 Thanks!!! I will try your way later. – Bo-Yuan Oct 24 '16 at 14:04
  • @dr01 Fantastic! It worked!! Thanks!! – Bo-Yuan Oct 24 '16 at 14:21