Skip to content
Advertisement

Bash script to pull variable credentials from another file using “. filename”

Running Ubuntu 18.04 subsystem on Windows 10, but have also tried to do this on a Ubuntu 18.04 Google cloud virtual machine.

I’ve realised that baking my login credentials into my scripts is a rather dumb idea, not just for the security risks but because I’ll have to edit every script if I change my password…

I discovered that I should be able to have a file that contains my credentials and put them “inline” when I run my script by using “. file”, however when I run my script it just returns an error that the file isn’t found.

Using ls on the directory I run the script from contains:

  • test.sh
  • credential

“credential” file contents

USER=<username>
PWD=<password>

Current script for test.sh

#!/bin/bash

set -eu

DS=$(date "+%Y-%m-%d" -d "11 days ago")
DE=$(date "+%Y-%m-%d" -d "1 day ago")

. credential

rm -f cookiejar

curl  /dev/null -s -S -L -f -c cookiejar 'https://url/auth/authenticate' -d name=$USER -d passwd=$PWD

Error Message

+ set -eu
+ date +%Y-%m-%d -d 11 days ago
+ DS=2020-01-05
+ date +%Y-%m-%d -d 1 day ago
+ DE=2020-01-15
+ account=465
+ . credential test.sh: 9: .: credential: not found

I’ve tried messing around with the spaces between the “. credential” line of the script and tried to find out what I might be doing wrong online but haven’t been able to google search correctly to find a relevant answer.

Can someone confirm what I’m missing/ not aware of here or point me to documentation that might help? This is my first time trying to do something like this so apologies if this is a basic question.

Advertisement

Answer

. uses path lookup to find the file named by its argument. Since the current working directory typically is not in your PATH (nor should it), . won’t find the file. Instead, use

. ./credential

to bypass PATH lookup.

This isn’t really safe, though, because now you are restricted to running the script from the proper directory. Either put credential in a directory on your PATH, or use an absolute path to specify where credential is located.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement