Home > database >  Using Vim commands in a Bash Script
Using Vim commands in a Bash Script

Time:01-12

so im trying to create a bash script that runs on MAC command line to a remote server and uses some mv commands to move some files around but i also need it to open up a file and add a line to the top of the file and save it in the middle of the script heres what i have so far:



(this is adjusting permissions so i can edit the file)
chef-client -r xxxxxxredactedxxxxxxredacted
cd /xxx/postgresql/xx/main/
Sudo chmod -R 775 filenamehere
sudo chown -R postgres:postgres filenamehere



read -p 'Enter the IP: ' ip


echo "Enter the file name :"
read -r filename

  echo "Type this below: host all all "$ip"/24 trust : "
read -r line

cd /etc/postgresql/12/main/
printf '1i\n%s\n.\nwq\n' "$line" | ed "$filename".   <-- **this is the problem line**


^ this command gives me permission denied because of access, for some reason i can edit it with vim but not this command

its worth noting these commands arent ran through my pc so my ability to move files is somewhat limited, its ran through SSM ing into an IP of a test enviroment through my command line

Normally I manually VIM into the file and add a line to the top

CodePudding user response:

Don't know if you're using echo to output the prompts because you didn't know about the -p read option or you wanted the new lines.

You could use command grouping to add a line at the top of your file.

read -p "Have you copied a file to the data shipper? (yes/no)"

if [ "$REPLY" == "yes" ]; then
    read -p "Enter a variable: " VARIABLE
    
    read -p "Enter a file name: " FILE
    
    cd /var/xxxredacted////
    cd /tmp/
    sudo mv "$FILE" /varxxxredactedxxxxxxxx/drop
    cd /var/redactedxxxxredactedxx/drop
    sudo unzip "$FILE"
fi

read -p "Enter the file name:\n" FILENAME
read -p "Enter the line to be added:\n" LINE

{ echo $LINE; cat "$FILENAME"; } > "${FILENAME}.new"
mv "$FILENAME"{.new,}

sed could be used too, if the line had to go to a specific line :

# If \n is omnited, $LINE will just be inserted on 
# line 1 instead of appending a new line
sed -i "${LINENB}s/$LINE\n/" $FILENAME
  • Related