Score:0

How to make commad as variable in shell scrpit

in flag

I wrote a script to check file exit then check if that file have given line, and finally print that line, here is this

#!user/bin/bash
echo "$1 $2"
if [ -e "$1" ]; then
    if [ "$(wc -l "$1")" -ge 1 ]; then
        sed -n "1p" "$1"
    fi
fi

But it return error like Illegal number: 3 /home/k/Documents/text.txt

My question is, how to make wc -l "$1" as a variable?

Score:3
hr flag

The default output of wc -l file includes the filename as well as the count.

$ wc -l file
8 file

As a workaround, you can redirect the file content to wc -l via the shell's standard input stream:

$ wc -l < file
8

So

if [ "$(wc -l < "$1")" -ge 1 ]; then
    sed -n "1p" "$1"
fi
in flag
Thanks , it work !!
Score:1
tr flag
ash

Only keep the first field in the wc output. Awk is my favorite tool for that:

wc -l "$1" | awk '{ print $1 }'

To capture this in a variable:

COUNT="$(wc -l "$1" | awk '{print $1}')"
in flag
Thank for your answer
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.