0

Trying to store to a variable, a specific section (type of file) from the response of the file command.

The first echo line, the one that is piped into cut, already outputs the correct information on screen. However, I need to later use that in conditioning, so it's required to store this in the 'type' variable. I have tried various ways but they didn't work, for example type=$(($cmd) | cut -d " " -f 2), as well as using redirects and pipes.

#! /usr/bin/env bash


    cmd="archive"
    type=""

    cmd="file $cmd"
    echo $($cmd) | cut -d " " -f 2

    type=???

    echo "File Type is: $type"
  • See [BashFAQ #1](https://mywiki.wooledge.org/BashFAQ/001). – Charles Duffy May 27 '22 at 12:50
  • That said, you know how to do `| cut -d" " -f2` -- combine that with the linked duplicate I'm about to provide, and you have your answer. – Charles Duffy May 27 '22 at 12:50
  • Or `read -r _ type _ < <(file archive)` to put only the second word of the output of `file archive` into the variable named `type`, without needing `cut` at all. The FAQ I mentioned above covers that (and [BashFAQ #24](https://mywiki.wooledge.org/BashFAQ/024) explains the `< <(...)` idiom). – Charles Duffy May 27 '22 at 12:52
  • Also, `$($cmd)` is an antipattern (as is storing commands in strings in general). See [BashFAQ #50](https://mywiki.wooledge.org/BashFAQ/050) describing why it's unreliable and what to do instead. – Charles Duffy May 27 '22 at 12:53

0 Answers0