roachsinai
roachsinai

Reputation: 536

Bash run command according to environment variable

See I wanna copy a file to a destination: cp filename /home/example/temp.txt.

The question the filename will be changed by some programes, and the new name of it will be written in file /home/example/.env.

What I want is alias something like alias cpf=cp ${filename} /home/nope/temp.txt to .bashrc, then what I need is only run cpf if I want to copy the latest finename to /home/example/temp.txt.


What I have tried:

eval $(grep -v "^#" "/home/example/.env") cp ${filename} /home/nope/temp.txt

and faild to get ${filename}.

Is there some changes to make what I tried work?

Upvotes: 0

Views: 343

Answers (2)

Walter A
Walter A

Reputation: 20032

Example .env:

key1='do not put me in the environment'
key2=1231
filename=thisvaluechanges
key4="I hate being evaluated"

You only want to evaluate the line with filename. First test how you can select that line, something like

grep "^filename=" /home/example/.env
# or
sed -n 's/^\s*filename\s*=\s*/filename=/p' /home/example/.env

Next you can source the selected line.

source <(grep "^filename=" /home/example/.env)

When the filename is a fixed string (without $() that needs to be evaluated), you can do without source:

cp $(grep "^filename=" /home/example/.env) /home/nope/temp.txt

Before putting this in an alias, remember that a function can do everything an alias can, and can do more. You "should" stop using alias.
When you have three or four files like filename1, 2, 3, 4, you can use a function with an argument:

cpf() {
   if (( $# = 0 )); then
      echo "Usage: cpf filenumber"
   else
      cp $(grep "^filename${1}=" /home/example/.env) /home/nope/temp.txt
   fi
}

You can call the function with cpf 2 for filename2.
When you want to put the filename in the environment, you can change the function

source <(grep "^filename${1}=" /home/example/.env)

Upvotes: 2

KamilCuk
KamilCuk

Reputation: 142025

My guess is that assuming /home/example/.env contains:

#!/bin/bash
# bash sourcable file
filename=$(echo 123)

then you want:

#!/bin/bash
cpf() {
   (
      . /home/example/.env
      cp "$filename" /home/nope/temp.txt
   )
}

Notes:

  • eval is evil. Your use of eval $(grep...) is very dangerous.
  • Always remember to qoute your expansions.

Upvotes: 1

Related Questions