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?

1
  • I'm pretty sure you could just go with x=$(file $1) Commented Dec 6, 2019 at 10:54

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.