3

Using bash in a Debian system.

bash --version
GNU bash, version 4.4.12(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

I defined an alias inside a function. I use this alias to write to a log file. Since I run this command as non-privileged user, I'm using tee to do this: alias is not found.

I get:

./test.sh 
Preparing Environment...
/tmp/support/20200525_074655
./test.sh: line 19: WRITE_LOG: command not found
./test.sh: line 20: ifconfig: command not found
./test.sh: line 20: WRITE_LOG: command not found

test.sh

#!/bin/bash


function prepare_environment() {
    echo "Preparing Environment..."
    TICKET_ID=$(date '+%Y%m%d_%H%M%S')
    LOG_LOCATION=/tmp/support/"${TICKET_ID}"
    sudo mkdir -p "${LOG_LOCATION}" 
    echo "${LOG_LOCATION}"
    alias WRITE_LOG='sudo tee -a "${LOG_LOCATION}"/report.log  > /dev/null'
}

function write_log() {
    sudo tee -a "${LOG_LOCATION}"/report.log  > /dev/null
}


function collect_information() {
    echo "Current Report time: $(date '+%Y/%m/%d %H:%M.%S')" | WRITE_LOG
    ifconfig | WRITE_LOG
}   

prepare_environment
echo "Current Report time: $(date '+%Y/%m/%d %H:%M.%S')" | write_log
collect_information

Alternatives:

  • I have various commands, instead of doing sudo command > file.log I though this would be a cleaner way to do it.
  • I can do sudo command | write_log

Similar question

1
  • If you have to use sudo, then why not just run the script as root? May 25, 2020 at 8:08

1 Answer 1

3

Bash does not expand aliases in scripts by default, only when it's interactive.

You can enable alias expansion, but there's no point. Just use the function.


As for ifconfig, you can use it as an unprivileged user to obtain information, but not to modify the system configuration. Many distributions don't put it in the PATH of unprivileged users. Add sbin directories to the PATH in your script:

PATH=/usr/local/sbin:/usr/sbin:/sbin:$PATH
1
  • Uprated because you have the core answer, although "there's no point" is a judgement, and hard to justify without looking at the particular case.
    – AdamC
    Feb 10, 2023 at 17:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .