The following code forms a string (import statement), reads content from handler.js with awk, appends text after matched context "shell added import", then overwrite the file.
#!/bin/zsh
# setting path for project folders
HANDLER_PATH=${pwd}"workers/model/"
# just an import statement - being used as string
local IMPORT_TEXT=(import ${MAIN_FUNCTION} from "'./model/${MODEL_NAME}/${MODEL_NAME}'")
awk -v text=${IMPORT_TEXT} '1;/shell added import/{print text}' ${HANDLER_PATH}handler.js > ${HANDLER_PATH}handler.js_tmp && mv ${HANDLER_PATH}handler.js_tmp ${HANDLER_PATH}handler.js
Instead, it throws error [cannot read file]
Thing to note, it works in shell, but not from script.sh. Also, this similar code works on other files, as well as script. Adding permissions for the same:
Other file: -rw-r--r-- 1 user staff 9384
handler.js: -rw-r--r-- 1 user staff 7453
As per other thread i referred, it is "some permission issue if it works from terminal but not from script"
Any help is appreciated!
It sounds like this is what you're really trying to do (untested):
#!/usr/bin/env bash
# setting path for project folders
handler_path="$PWD/workers/model"
hdlr="$handler_path/handler.js"
tmp="${hdlr}_tmp"
# just an import statement - being used as string
import_text="import $MAIN_FUNCTION from \"'./model/$MODEL_NAME/$MODEL_NAME'\""
awk -v text="$import_text" '
{ print }
/shell added import/ { print text }
' "$hdlr" > "$tmp" &&
mv -- "$tmp" "$hdlr"
I expect that'd work as-is in zsh too if you prefer that shell.