1

I have a script that gets the filenames in a folder and creates HTML link to them on my homepage. Here is the script:

#!/bin/bash  
list_dir=`ls -t /path/to/dir/`
for i in $list_dir   
do  
echo `'<a href="/path/to/dir/$i">$i</a>' >> /var/www/index.html`   
done

But when I check the var/www/index.html the code is submitted, but the variables have not been substituted. Any advice on how to fix this?

3

There is a reason both single quotes ' and double quotes " exist. Parameters get expanded within double quotes but not within single quotes.

echo "<a href=\"/path/to/dir/$i\">$i</a>" >> /var/www/index.html
1

The problem is that you have single quotes wrapping the variables. You're variables are considered literals when wrapped by singled quotes. Try switching them to double quotes instead.

You also need to remove the back ticks around the "echo ...". Those exec a sub-shell which gives you this error:

a: line 5: <a href="/path/to/dir/file1">file1</a>: No such file or directory

a: line 5: <a href="/path/to/dir/file2">file2</a>: No such file or directory

This script does what you need:

#!/bin/bash
list_dir=`ls -t /path/to/dir/`
for i in $list_dir
do
echo "<a href=\"/path/to/dir/$i\">$i</a>" >> /var/www/index.html
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.