Printf splits a string at spaces - Bash -
this question has answer here:
i'm having troubles printf function in bash. wrote little script on pass name , 2 letters (such "sh", "py", "ht") , creates file in current working directory named "name.extension". instance, if execute seed test py file named test.py created in current working dir shebang #!/usr/bin/python3.
so far, good, nothing fancy: i'm learning shell scripting , thought simple exercise test knowledge gained far. problem when want create html file. function use:
creahtml(){ head='<!--doctype html-->\n<html>\n\t<head>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n\t</body>\n</html>' percorso=$cartella_corrente/$nome_file.html printf $head>>$percorso chmod 755 $percorso } if run, instance, seed test ht correct function (creahtml) called, test.html created if try see:
<!--doctype and nothing else. trace function:
[sviluppo:~/bin]$ seed test ht + creahtml + head='<!--doctype html-->\n<html>\n\t<head>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n\t</body>\n</html>' + percorso=/home/sviluppo/bin/test.html + printf '<!--doctype' 'html-->\n<html>\n\t<head>\n\t\t<meta' 'charset=\"utf-8\">\n\t</head>\n\t<body>\n\t</body>\n</html>' + chmod 755 /home/sviluppo/bin/test.html + set +x however, if try run printf '<!--doctype html-->\n<html>\n\t<head>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n\t</body>\n</html>' terminal, see correct output: "skeleton" of html file neatly displayed indentation , everything. missing here?
try echo -e instead of printf. printf printing formatted strings. since didn't protect $head quotes, bash splits string form command. first word (before first white space) forms format string. rest arguments things didn't specify print.
echo -e "$head" > "$percorso" the -e evaluates \n newlines. changed >> > since looks want whole file, rather append existing file might have.
you have careful quotes in bash. 1 thing can become many things. makes more powerful, can confusing people learning. notice put file name "$percorso" in double quotes too. evaluates variable , makes sure ends 1 thing. if use single quotes, 1 word, not evaluated. unlike python, there big difference between single , double quotes.
if want use printf compatibility @chepner pointed out, sure quote it:
printf "$head" > "$percorso" actually simpler anyway.
Comments
Post a Comment