0

I need to assign a variable $x value that returns from the command 'file' on $1. my code is:

echo $1 | xargs file 'x=$'

and the last part x=$ does not work. I need that if the argument $1 is 'archive.zip' then the variable x will get the value of the command 'file' on it. How can I do that?

Yennefer
  • 5,704
  • 7
  • 31
  • 44
riki
  • 19
  • 7

1 Answers1

2

Assign value to a variable in shell script is like below

  a=$(echo $1 | xargs file)

The above means that execute what is inside $(...) and the output will be assigned to a variable with name a Access contents of variable a

 echo $a

You can execute also directly the file command with argument the file name and then store the output to a variable.

$1 is a special argument and its the first argument that used to call a script.

Example1:

root@server[/root] > echo wiki.20191206.tar.gz | xargs file
wiki.20191206.tar.gz: gzip compressed data, from Unix, last modified: Fri Dec  6 00:00:01 2019
root@server[/root] > a=$(echo wiki.20191206.tar.gz | xargs file)
root@server[/root] > echo $a
wiki.20191206.tar.gz: gzip compressed data, from Unix, last modified: Fri Dec 6 00:00:01 2019

Example2:

root@server[/root] > file wiki.20191206.tar.gz
wiki.20191206.tar.gz: gzip compressed data, from Unix, last modified: Fri Dec  6 00:00:01 2019
root@server[/root] > a=$(file wiki.20191206.tar.gz)
root@server[/root] > echo $a
wiki.20191206.tar.gz: gzip compressed data, from Unix, last modified: Fri Dec 6 00:00:01 201
igiannak
  • 104
  • 1
  • 11
  • 1
    This question is clearly a duplicate (so is your answer). Next time you encounter such a question, instead of posting an answer, just flag and move on please – oguz ismail Dec 06 '19 at 10:28